创建:
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); }