码迷,mamicode.com
首页 > 系统相关 > 详细

linux信号量使用

时间:2016-04-19 00:21:48      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

#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); }

 

linux信号量使用

标签:

原文地址:http://www.cnblogs.com/wzben/p/5406422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!