linux信号量使用

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


sem_t sem1,sem2;

void func1(char * string){

    int i = 0;
    
    while(i<100){
    
    sem_wait(&sem1);

    printf("%s\n",string);
    i++;

    
    sem_post(&sem2);
  //因为sem2 在 fun2里面被用掉了,并没有post。
  //等fun1输出完成之后,再post,fun2就wait到了sem2,确保了fun1和fun2能交替运行
} }
void func2(char * string){ int i = 0; while(i<100){ sem_wait(&sem2); printf("%s\n",string); i++; sem_post(&sem1); } } int main(){ sem_init(&sem1,0,1); sem_init(&sem2,0,1); pthread_t tid1,tid2; pthread_create(&tid1,NULL,(void *)func1,"In A Thread!"); pthread_create(&tid2,NULL,(void *)func2,"In B Thread!"); pthread_join(tid1,NULL); pthread_join(tid2,NULL); }

 

posted @ 2016-04-18 23:33  wzb的QQ空间  阅读(706)  评论(0编辑  收藏  举报