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