// 保证多线程安全,处理多线程共同竞争某一资源:线程池队列#ifndef LOCKER_H#define LOCKER_H#include <exception>#include <pthread.h>#include <semaphore.h>// ************************线程同步机制封装类************************// 互斥锁类--->操作工作队列class locker {public: locker() { // 初始化互斥锁 if (pthread_mutex_init(&m_mutex, NULL) != 0) { throw std::exception(); // 抛出异常 } } ~locker() { // 析构 pthread_mutex_destroy(&m_mutex); } bool lock() { // 上锁 return pthread_mutex_lock(&m_mutex) == 0; } bool unlock() { // 解锁 return pthread_mutex_unlock(&m_mutex) == 0; } pthread_mutex_t* get() { // 获取互斥量 return &m_mutex; }private: pthread_mutex_t m_mutex; // 一个互斥锁 };// 条件变量类--->取子线程class cond {public: cond() { // 初始化条件变量 if (pthread_cond_init(&m_cond, NULL) != 0) { throw std::exception(); // 抛出异常 } } ~cond() { // 析构 pthread_cond_destroy(&m_cond); } bool wait(pthread_mutex_t* mutex) { return pthread_cond_wait(&m_cond, mutex) == 0; } bool timewait(pthread_mutex_t* mutex, struct timespec t) { return pthread_cond_timedwait(&m_cond, mutex, &t) == 0; } bool signal() { // 唤醒一个或多个线程 return pthread_cond_signal(&m_cond) == 0; } bool broadcast() { // 将所有线程都唤醒 return pthread_cond_broadcast(&m_cond) == 0; }private: pthread_cond_t m_cond;};// 信号量类--->记录个数class sem {public: sem () { // num = 0的析构函数 if (sem_init(&m_sem, 0, 0) != 0) { throw std::exception(); } } sem (int num) { // num自设的析构函数 if (sem_init(&m_sem, 0, num) != 0) { throw std::exception(); } } ~sem () { // 析构 sem_destroy(&m_sem); } bool wait() { // 等待信号量(为0阻塞,大于0就-1) return sem_wait(&m_sem) == 0; } bool post() { // 增加信号量 return sem_post(&m_sem) == 0; }private: sem_t m_sem;};# endif