1. // 保证多线程安全,处理多线程共同竞争某一资源:线程池队列
    2. #ifndef LOCKER_H
    3. #define LOCKER_H
    4. #include <exception>
    5. #include <pthread.h>
    6. #include <semaphore.h>
    7. // ************************线程同步机制封装类************************
    8. // 互斥锁类--->操作工作队列
    9. class locker {
    10. public:
    11. locker() { // 初始化互斥锁
    12. if (pthread_mutex_init(&m_mutex, NULL) != 0) {
    13. throw std::exception(); // 抛出异常
    14. }
    15. }
    16. ~locker() { // 析构
    17. pthread_mutex_destroy(&m_mutex);
    18. }
    19. bool lock() { // 上锁
    20. return pthread_mutex_lock(&m_mutex) == 0;
    21. }
    22. bool unlock() { // 解锁
    23. return pthread_mutex_unlock(&m_mutex) == 0;
    24. }
    25. pthread_mutex_t* get() { // 获取互斥量
    26. return &m_mutex;
    27. }
    28. private:
    29. pthread_mutex_t m_mutex; // 一个互斥锁
    30. };
    31. // 条件变量类--->取子线程
    32. class cond {
    33. public:
    34. cond() { // 初始化条件变量
    35. if (pthread_cond_init(&m_cond, NULL) != 0) {
    36. throw std::exception(); // 抛出异常
    37. }
    38. }
    39. ~cond() { // 析构
    40. pthread_cond_destroy(&m_cond);
    41. }
    42. bool wait(pthread_mutex_t* mutex) {
    43. return pthread_cond_wait(&m_cond, mutex) == 0;
    44. }
    45. bool timewait(pthread_mutex_t* mutex, struct timespec t) {
    46. return pthread_cond_timedwait(&m_cond, mutex, &t) == 0;
    47. }
    48. bool signal() { // 唤醒一个或多个线程
    49. return pthread_cond_signal(&m_cond) == 0;
    50. }
    51. bool broadcast() { // 将所有线程都唤醒
    52. return pthread_cond_broadcast(&m_cond) == 0;
    53. }
    54. private:
    55. pthread_cond_t m_cond;
    56. };
    57. // 信号量类--->记录个数
    58. class sem {
    59. public:
    60. sem () { // num = 0的析构函数
    61. if (sem_init(&m_sem, 0, 0) != 0) {
    62. throw std::exception();
    63. }
    64. }
    65. sem (int num) { // num自设的析构函数
    66. if (sem_init(&m_sem, 0, num) != 0) {
    67. throw std::exception();
    68. }
    69. }
    70. ~sem () { // 析构
    71. sem_destroy(&m_sem);
    72. }
    73. bool wait() { // 等待信号量(为0阻塞,大于0就-1)
    74. return sem_wait(&m_sem) == 0;
    75. }
    76. bool post() { // 增加信号量
    77. return sem_post(&m_sem) == 0;
    78. }
    79. private:
    80. sem_t m_sem;
    81. };
    82. # endif