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);
    }
  • 相关阅读:
    Codeforces Round #443 Div. 1
    linux中ps命令
    占cpu 100%的脚本
    检查Linux系统cpu--内存---磁盘的脚本
    jQuery对象的属性操作
    关于js的一些收集
    Linux命令集合
    使用python操作excel表格
    Linux7.3系统 升级python到3.6使用ping主机脚本
    一个别人的线程池的编写
  • 原文地址:https://www.cnblogs.com/farbeyond/p/4477257.html
Copyright © 2011-2022 走看看