linux sem信号量使用
来源:互联网 发布:淘宝管控记录有影响吗 编辑:程序博客网 时间:2024/05/17 02:44
Linux下关于信号量结构体表示为:sem_t
操作结构体的函数:
初始化函数: sem_init(sem_t * __sem,int __pshared,unsigned int __value);
触发信号量值:sem_post(sem_t * __sem);
等待信号量触发:
通常有:
一直等待:sem_wait(sem_t * __sem);
测试__sem是否触发:sem_trywait(sem_t * __sem);
等待超时:sem_timedwait(sem_t * __restrict __sem, __ const struct timespec * __restrict __abstime);
释放销毁信号量:
sem _destroy(sem_t * __sem);
例子:
(关于主进程等待线程问题,仍有疑问,但是可以用join实现,也可以设置变量来判断,这边暂时使用sleep,治标不治本,等待巧妙的方法来实现进程等多线程问题)
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "semaphore.h"
#include "sys/time.h"
#include "assert.h"
#include "errno.h"
#include "signal.h"
#include "pthread.h"
#include "time.h"
void* thread1(void*);
void* thread2(void*);
void* thread3(void*);
int alex=0;
sem_t sem12;
sem_t sem13;
int main()
{
pthread_t pid1,pid2,pid3;
printf("--enter main:\n");
int ret=sem_init(&sem12,0,0);
if(ret!=0)
{
printf("sem12 init Fail\n");
return ret;
}
ret=sem_init(&sem13,0,0);
if(ret!=0)
{
printf("sem13 init Fail\n");
return ret;
}
pthread_create(&pid1,NULL,thread1,NULL);
pthread_create(&pid1,NULL,thread2,NULL);
pthread_create(&pid1,NULL,thread3,NULL);
sleep(6);
sem_destroy(&sem12);
sem_destroy(&sem13);
printf("--end:\n");
exit(0);
}
void* thread1(void* arg)
{
printf("this is thread1:\n");
int input;
printf("put an number: \n");
scanf("%d",&input);
printf("the number is: %d\n",input);
//sleep(2);
sem_post(&sem12);
sem_post(&sem13);
printf("leave thread1\n");
pthread_exit(0);
}
void* thread2(void* arg)
{
printf("this is thread2:\n");
sem_wait(&sem12);
printf("leave thread2\n");
pthread_exit(0);
}
void* thread3(void* arg)
{
struct timespec ts;
printf("this is thread3:\n");
ts.tv_sec=time(NULL)+5;
int s=sem_timedwait(&sem13,&ts);
if(s==-1)
printf("thread wait timeout\n");
printf("leave thread3\n");
pthread_exit(0);
}
- linux sem信号量使用
- Linux sem信号量使用
- linux---信号量--------sem的使用,可以用到多进程中。
- sem信号量
- sem 信号量
- 信号量sem
- Linux进程间通讯之信号量sem
- linux SysV IPC sem信号量实现
- Linux线程同步机制四--信号量sem
- 信号量sem简介
- IPC-sem 信号量
- SEM 信号量线程控制
- 关于信号量sem
- 信号量(sem)
- IPC信号量 sem
- 多值信号量(sem)
- linux下C的 信号量 函数(sem开头的那一簇)的实践
- linux 信号量使用
- 动态链接库*.so的编译与使用
- [EDI]EDI的报文标准和代码标准
- Gvim移动命令
- Oracle 阻塞
- ViewPager example -实现左右两个屏幕的切换
- linux sem信号量使用
- c++ 怎么以二进制形式存储
- surfaceview 双缓冲的理解
- 为VIM配置多窗口管理器。
- ffmpeg 移植到 android
- java 调用存储过程
- java 位运算符
- android 中系统自带的主题与样式(theme and style)
- .reg文件格式