• 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);
    }
  • 相关阅读:
    ABAP TCode
    SAP 常用的事务代码
    SAP FI TCode
    Little Tutorials的一篇文章断言:UML(统一建模语言)正在死亡:
    SAP PP TCode
    [ZT]解密中国IT人十大职业现状
    User Exit Query
    SAP客户端多语言设置
    一个女CIO的诞生
    DIY防奸手册之 主流硬盘型号解惑篇
  • 原文地址:https://www.cnblogs.com/farbeyond/p/4477257.html
Copyright © 2020-2023  润新知