线程同步——信号量
2016-07-15 09:43
399 查看
线程同步互斥中信号量的使用
// 线程同步之信号量(注意和IPC信号量的区别,IPC信号量用于进程间通信) #include <iostream> #include <string> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <semaphore.h> using namespace std; // 信号量 sem_t sem; // 公共缓冲区,给生产者和消费者读写 char common_buffer[64]; // 生产者线程 void* producer(void* data) { int count = 0; while(count < 64) { ++count; // 往缓冲区中填充数据 sprintf(common_buffer,"%d",count); // 激活信号量,即P操作 sem_post(&sem); sleep(1); } } // 消费者线程 void* consumer(void* data) { int count = 0; while(count < 64) { // 等待信号量的值变成1,即V操作 sem_wait(&sem); // 消耗数据 printf("%s\n",common_buffer); ++count; } } // 主函数 int main(int argc,char* argv[]) { // 初始化信号量 sem_init(&sem,0,0); // 定义两个线程id pthread_t thd1,thd2; // 创建生产者和消费者线程 pthread_create(&thd1,0,consumer,0); pthread_create(&thd2,0,producer,0); // 等待两个线程运行结束 pthread_join(thd1,0); pthread_join(thd2,0); // 销毁信号量 sem_destroy(&sem); return 0; }
相关文章推荐
- android学习15#--简单自定义跑马灯textView控件
- iOS设置圆角的三种方式
- JSON-handle(0.0.1.3)转载自http://www.chromein.com/crx_12022.html
- Android开发中EditText一些用法
- Linux下更改目录及其下的子目录和文件的访问权限
- 为数组分组,使两组中各元素加起来的和相等
- 巧用svn create patch(打补丁)方案解决定制版需求
- HTC M9 刷机教程(存档备忘)
- 仿LOL项目开发第七天
- Android手机 Fildder真机抓包
- 欧几里德算法扩展
- CSS3 border
- 软件之最大全电子书免费版
- 仿LOL项目开发第七天
- PAT 团体程序设计天梯赛-练习集 L2-009. 抢红包
- BitmapFactory
- checkbox的readonly属性设置
- bootstrap .col-md-6 文字居中问题处理
- Android事件传递机制
- OpenCV基础类容器Mat类详解