zoukankan      html  css  js  c++  java
  • Linux线程同步---信号量

    首先讲一下线程同步信号量的几个关键步骤!

    1、定义并初始化信号量。

      (1) sem_t bin_sem;

      (2)  res = sem_init(&bin_sem,0,0);

      详细步骤可以查看man帮助页面

      

    2、使用信号量

      (1) 信号量加1操作。sem_post(&bin_sem);

      (2) 信号量等待并减1操作。sem_wait(&bin_sem);   

      初始化后一般处于等待状态,执行某个操作后加1,而另个一个操作执行前进行等待操作。如果有多个线程,通常是一个线程进行加1操作,另外一个行程处于等待状态。

      关于信号量的死锁问题,这里暂不讨论。
      

    3、使用完毕即时销毁。

       sem_destroy(&bin_sem);

      因为信号量也是一种资源。用完就释放。

    下面是某个教程中的经典例子,干货如下。当然也可以查看man页面例子。
      

    #include<stdio.h>
    #include<unistd.h>
    #include<stdlib.h>
    #include<string.h>
    #include<pthread.h>
    #include<semaphore.h>
    
    void *thread_function(void *arg);
    sem_t bin_sem;
    
    #define WORK_SIZE 1024
    char work_area[WORK_SIZE];
    
    int main(){
        int res;
        pthread_t a_thread;
        void *thread_result;
        res = sem_init(&bin_sem,0,0);
        if(res != 0){
            perror("Semaphore initialization failed!
    ");
            exit(EXIT_FAILURE);
        }
        res = pthread_create(&a_thread,NULL,thread_function,NULL);
        if(res != 0){
            perror("Thread creation failed");
            exit(EXIT_FAILURE);
        }
        printf("Input some text. Enter 'end'to finihed");
        while(strncmp("end",work_area,3) != 0){
            fgets(work_area,WORK_SIZE,stdin);
            sem_post(&bin_sem);
        }
        printf("
    Wainting for theread to finish...
    ");
        res = pthread_join(a_thread,&thread_result);
        if( res !=0){
            perror("Thread join failed");
            exit(EXIT_FAILURE);
        }
        printf("Thread joined
    ");
        sem_destroy(&bin_sem);
        exit(EXIT_FAILURE);
    }
    
    void *thread_function(void *arg){
        sem_wait(&bin_sem);
        while(strncmp("end",work_area,3) != 0){
            printf("You input %d characters
    ",strlen(work_area)-1);
            sem_wait(&bin_sem);    
        }
        pthread_exit(NULL);
    }
  • 相关阅读:
    C#中创建Android项目
    C#中创建Android项目
    在C#中获取当前屏幕的分辨率的方法
    数据库面试
    计算机网络面试
    linux面试
    Java使用递归检索文件个数
    二分查找
    富途证券面经(一面挂)
    Mysql
  • 原文地址:https://www.cnblogs.com/farbeyond/p/4477257.html
Copyright © 2011-2022 走看看