Linux下的信号灯semaphore的应用
来源:互联网 发布:网络账号被盗报警 编辑:程序博客网 时间:2024/05/31 13:15
如果使用mutex_lock,mutex_unlock方式同步操作,如果当很长一段时间内都没有任何操作,
但是线程依然会不停地执行lock,unlock操作。所以这样的做法是完全没有任何的意义的。
Linux系统还提供了另外一种同步机制,信号灯,Semaphore。使用方法如下例子:
示例说明:一个线程在控制台输入,另一个线程将输入的结果打印显示。
示例代码如下:
#include "pthread_head.h"sem_t sem;char buf[SIZE];void *tfn1(void *arg){ int i; for(i = 0; ; i++){sem_wait(&sem); //p操作if(strncmp(buf,"quit",4) == 0) break;printf("%s",buf); } return (void*)0;}void *tfn2(void *arg){ int i; for(i = 0; ; i++){fgets(buf,SIZE,stdin);sem_post(&sem); //v操作if(strncmp(buf,"quit",4) == 0) break; } return (void*)0;}int main(void){ pthread_t tid1,tid2; sem_init(&sem,0,0); if(pthread_create(&tid1,NULL,tfn1,NULL) < 0)p_error("pthread_create"); if(pthread_create(&tid2,NULL,tfn2,NULL) < 0)p_error("pthread_create"); if(pthread_join(tid1,NULL) < 0)p_error("pthread_join"); if(pthread_join(tid2,NULL) < 0)p_error("pthread_join"); return 0;}
0 0
- Linux下的信号灯semaphore的应用
- Linux semaphore POSIX信号灯的Hello World
- linux下信号量semaphore的应用
- linux下信号量semaphore的应用
- Linux下信号灯的使用
- Unix,Linux下的信号灯
- 信号灯的典型应用
- 信号灯的应用
- linux下的信号量(semaphore)
- Linux的进程编程-之二-进程间通信(信号灯-Semaphore)
- 控制并发访问的线程数 Semaphore 信号灯
- semaphore信号灯
- Semaphore 信号灯
- semaphore信号灯
- Linux 下进程间通信机制(六) 信号灯集 Semaphore Arrays
- unix多线程,互斥锁和信号灯的应用
- java多线程-Semaphore信号量使用 介绍 信号量(Semaphore),有时被称为信号灯,是在多线程环境下使用的一种设施, 它负责协调各个线程, 以保证它们能够正确、合理的使用公共资源
- Semaphore和Mutex -- Linux下的互斥机制分析
- 职场分享:成功则的职场态度
- docker入门指引之在ceontos6.5下搭建docker的测试环境
- [ACM] POJ 1061青蛙的约会(扩展欧几里得求模线性方程)
- STL中map、set的数据结构及底层实现
- rsync
- Linux下的信号灯semaphore的应用
- 解决UINavigationController+UITabbar跳转页面隐藏tabbar的一种方法
- LUA面向对象程序设计(一)类
- 个人收集关于js跨域的资料
- HBase中的备份和故障恢复方法
- gaodywahebwajbewagjkwa21
- Jquery-Validation自定义校验方法
- POJ 2060-Taxi Cab Scheme
- Linux(CentOS)下,下载安装Tomcat并配置