Linux互斥锁和条件变量

时间:2021-03-18 18:08:24
#include <pthread.h>

class thread_lock
{
public:
thread_lock()
{
pthread_mutexattr_init(&m_mutexatr);
//互斥锁重复上锁,不会引起死锁,一个线程对这类互斥锁的多次重复上锁必须由这个线程来重复相同数量的解锁,这样才能解开这个互斥锁,别的线程才能//得到这个互斥锁
pthread_mutexattr_settype(&m_mutexatr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&m_mutex, &m_mutexatr);
pthread_cond_init(&m_cond, NULL);
}

~thread_lock()
{
pthread_mutexattr_destroy(&m_mutexatr);
pthread_mutex_destroy(&m_mutex);
pthread_cond_destroy(&m_cond);
}

void lock()
{
pthread_mutex_lock(&m_mutex);
}

void unlock()
{
pthread_mutex_unlock(&m_mutex);
}

void wait()
{
pthread_cond_wait(&m_cond, &m_mutex);
}

void signal()
{
pthread_cond_signal(&m_cond);
}

private:
pthread_mutex_t m_mutex;
pthread_mutexattr_t m_mutexatr;
pthread_cond_t m_cond;
};

#endif
void read(){while (true){m_thread_lock.lock();if (m_list_task.empty()){m_thread_lock.wait();}task* ptask = m_list_task.front();m_list_task.pop_front();m_thread_lock.unlock();ptask->run();delete ptask;}}void write(task* ptask){m_thread_lock.lock();m_list_task.push_back(ptask);m_thread_lock.signal();m_thread_lock.unlock();}

刚开始使用条件变量的时候,一直都在想如果在read函数中m_thread_lock.wait()阻塞住了等待新的数据,那么另外的写线程在write中没法m_thread_lock.lock(),那么就没法发送m_thread_lock.signal(),也就是没法触发read县城了,就会造成永远阻塞的结果了。读了多线程手册才发现,pthread_cond_wait的实际作用。

线程调用pthread_cond_wait这个函数之后,内核会做下面这些事:
1. 拿到锁的线程,把锁暂时释放;
2. 线程休眠,进行等待;
3. 线程等待通知,要醒来。(重新获取锁)
线程库将上面三步做成了原子性操作,和Linux内核绑定在一起。