zoukankan      html  css  js  c++  java
  • 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
    ",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 ",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); }
  • 相关阅读:
    eclipse CreateProcess error=87
    排序与查找
    利用Excel导出sql语句
    Java 反射机制总结
    MySQL问题
    异常解决
    MySQL连接不上
    工作时总结
    笔记
    注意
  • 原文地址:https://www.cnblogs.com/wzben/p/5406422.html
Copyright © 2011-2022 走看看