我们在编写线程处理的代码时,经常遇到线程同步或线程加锁,例如访问临界资源,这就需要对临界资源加锁防止访问冲突;再比如在处理通信时(TCP、MQTT)等,发送数据后需等待数据接收返回,通信过程本身又是异步的,这就需要线程等待。处理这些情况时,我封装了一个类,给大家分享。
头文件
#include <pthread.h>
#include <sys/time.h>
// 线程事件通知类封装,处理线程同步加锁、解锁、等待和信号发送
class CThreadNotifyHandle {
public:
CThreadNotifyHandle();
~CThreadNotifyHandle();
// 线程互斥锁,加锁
void lock() { pthread_mutex_lock(&m_mutex); }
// 线程互斥锁,解锁
void unlock() { pthread_mutex_unlock(&m_mutex); }
//线程等待条件变量信号---不带时间
void wait() { pthread_cond_wait(&m_cond, &m_mutex); }
//线程等待超时条件变量信号---带时间
int timewait(int ms) {
struct timeval now;
struct timespec timeout;
gettimeofday(&now, NULL);
timeout.tv_sec = now.tv_sec + ms/1000;
timeout.tv_nsec = (now.tv_usec + ms%1000 * 1000) * 1000;
return pthread_cond_timedwait(&m_cond, &m_mutex, &timeout);
}
//发送信号
void signal() { pthread_cond_signal(&m_cond); }
private:
pthread_mutex_t m_mutex;
pthread_mutexattr_t m_mutexattr;
pthread_cond_t m_cond;
};
cpp文件
#include "CThreadNotifyHandle.h"
CThreadNotifyHandle::CThreadNotifyHandle() {
pthread_mutexattr_init(&m_mutexattr);
pthread_mutexattr_settype(&m_mutexattr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&m_mutex, &m_mutexattr);
pthread_cond_init(&m_cond, NULL);
}
CThreadNotifyHandle::~CThreadNotifyHandle() {
pthread_mutexattr_destroy(&m_mutexattr);
pthread_mutex_destroy(&m_mutex);
pthread_cond_destroy(&m_cond);
}