linux

来源:互联网 发布:windows 扩展屏幕 ipad 编辑:程序博客网 时间:2024/06/09 16:36
  1. #include <pthread.h>  
  2.   
  3. class thread_lock  
  4. {  
  5. public:  
  6.     thread_lock()  
  7.     {  
  8.         pthread_mutexattr_init(&m_mutexatr);  
  9. //互斥锁重复上锁,不会引起死锁,一个线程对这类互斥锁的多次重复上锁必须由这个线程来重复相同数量的解锁,这样才能解开这个互斥锁,别的线程才能//得到这个互斥锁  
  10.         pthread_mutexattr_settype(&m_mutexatr, PTHREAD_MUTEX_RECURSIVE);  
  11.         pthread_mutex_init(&m_mutex, &m_mutexatr);  
  12.         pthread_cond_init(&m_cond, NULL);  
  13.     }  
  14.   
  15.     ~thread_lock()  
  16.     {  
  17.         pthread_mutexattr_destroy(&m_mutexatr);  
  18.         pthread_mutex_destroy(&m_mutex);  
  19.         pthread_cond_destroy(&m_cond);  
  20.     }  
  21.       
  22.     void lock()  
  23.     {  
  24.         pthread_mutex_lock(&m_mutex);  
  25.     }  
  26.   
  27.     void unlock()  
  28.     {  
  29.         pthread_mutex_unlock(&m_mutex);  
  30.     }  
  31.   
  32.     void wait()  
  33.     {  
  34.         pthread_cond_wait(&m_cond, &m_mutex);  
  35.     }  
  36.   
  37.     void signal()  
  38.     {  
  39.         pthread_cond_signal(&m_cond);  
  40.     }  
  41.   
  42. private:  
  43.     pthread_mutex_t m_mutex;  
  44.     pthread_mutexattr_t m_mutexatr;  
  45.     pthread_cond_t m_cond;  
  46. };  
  47.   
  48. #endif  
[cpp] view plain copy
print?
  1. void read()  
  2. {  
  3.     while (true)  
  4.     {  
  5.         m_thread_lock.lock();  
  6.         if (m_list_task.empty())  
  7.         {  
  8.             m_thread_lock.wait();  
  9.         }  
  10.         task* ptask = m_list_task.front();  
  11.         m_list_task.pop_front();  
  12.         m_thread_lock.unlock();  
  13.         ptask->run();  
  14.         delete ptask;  
  15.     }  
  16. }  
  17.   
  18. void write(task* ptask)  
  19. {  
  20.     m_thread_lock.lock();  
  21.     m_list_task.push_back(ptask);  
  22.     m_thread_lock.signal();  
  23.     m_thread_lock.unlock();  
  24. }  

刚开始使用条件变量的时候,一直都在想如果在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内核绑定在一起。