线程的信号量

创建:

int  sem_init(sem_t* sem,int pshared,unsigned  int  value);

sem————信号量对象。

pshared——信号量类型:0为线程共享;<0为进程共享。

value———初始值。

返回值———0成功,-1失败。

销毁:

int sem_destroy(sem_t*  sem);

返回值————0成功,-1失败。

阻塞等待:

int sem_wait(sem_t*  sem);

返回值————0成功,-1失败。

非阻塞等待:

int  sem_trywait(sem_t* sem);

返回值————0成功,-1失败。

超时等待:

int sem_timedwait(sem_t* sem,struct timespec*  abstime);

abstime————等待时间。

返回值————0成功,-1等待超时。

触发:

int sem_post(sem_t*  sem);

返回值————0成功,-1失败。

代码:

#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>

void* func(void* arg){
	sem_wait(arg);
	printf("enter func\n");
	sleep(1);
	printf("do something\n");
	sleep(1);
	printf("level func\n");
	sem_post(arg);
}

int main(int argc,int argv[]){
	sem_t sem;
	sem_init(&sem,0,1);
	
	pthread_t tids[3];
	int i;
	for(i=0;i<3;i++){
		pthread_create(&tids[i],NULL,func,&sem);
	}
	for(i=0;i<3;i++){
		pthread_join(tids[i],NULL);
	}
	sem_destroy(&sem);

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值