linux
来源:互联网 发布:windows 扩展屏幕 ipad 编辑:程序博客网 时间:2024/06/09 16:36
- #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内核绑定在一起。
阅读全文
0 0
- linux
- linux
- Linux
- Linux
- LINUX!
- Linux
- linux
- linux
- linux
- Linux
- linux
- linux
- linux
- linux
- Linux
- linux
- linux
- Linux
- 理解阻塞非阻塞与同步异步
- Install ProcessMaker 3.1 or 3.2 in CentOS/RHEL 7
- Python爬虫框架之Scrapy详解
- 什么是java?
- Java IO底层原理
- linux
- Vivado Logic Analyzer中VIO核的使用
- 【python学习笔记】12:用matplotlib绘制3D函数图像
- 高性能mysql笔记(一)并发 事务 引擎
- [PAT-乙级]1061.判断题
- 笔记本安装双系统教程
- C++学习笔记
- 莫名其妙 对话框 create 失败, 错误见图
- Mockito 测试基本用法