一个简单的信号量的例子

1. 信号量

Linux提供了控制线程执行和访问代码临界区域的方法。其中最基本的两种办法是信号量和互斥量。

关于互斥量,笔者在Linux互斥量中介绍

本文只介绍semaphore.h 相关的信号量的简单的操作。关于信号量在笔者其他博客里有详细介绍。

Linux还有其他共享内存的方法。

2. 信号量相关函数


#include <semaphore.h>

int sem_init(sem_t *sem, int pshared, unsigned int value);//创建信号量

int sem_post(sem_t *sem);// +1操作

int sem_wait(sem_t *sem);//  -1操作

int sem_destroy(sem_t *sem); //销毁

3. 程序代码:

/***************************************
 *    @file            semaphore.c
 *    @brief        线程信号量
 *    @author        Windeal
 *    @date        2013/08/06
***************************************/

 
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
 
#define WORK_SIZE 1024    //
 
char work_area[WORK_SIZE];
sem_t bin_sem;
 
void *thread_function(void * arg);
 
int main(int argc,char * argv [ ])
{
    int ret ;
    void* thread_result;
    pthread_t a_thread;
 
    ret = sem_init(&bin_sem,0, 0);     //初始化信号量为0
    if (ret != 0) {
        perror("sem_init()  is failed! ");
        exit(EXIT_FAILURE);
    }
 
    ret = pthread_create(&a_thread, NULL, thread_function, NULL);
    if (ret != 0) {
        perror("thread create failed! ");
        exit(EXIT_FAILURE);
    }
 
    printf("Enter 'end' to finish! ");
    while (strncmp("end", work_area,3) != 0) {
        fgets(work_area, WORK_SIZE, stdin);
        sem_post(&bin_sem);           // 信号量+ 1 操作
    }
 
    printf("Waitint for thread join ");
    ret = pthread_join(a_thread, &thread_result);
    if (ret != 0) {
        perror("thread_join  failed! ");
        exit(EXIT_FAILURE);
    }
 
    printf("thread join() ");
    sem_destroy(&bin_sem);
    exit(EXIT_FAILURE);
 
}
 
void *thread_function(void * arg){
    sem_wait(&bin_sem);                  // 信号量- 1 操作
    while (strncmp("end", work_area,3) != 0){
        printf("you input %d charactor ", strlen(work_area)-1);
        sem_wait(&bin_sem);                  // 信号量- 1 操作
    }
    pthread_exit(NULL);
}
 

运行结果:

 

原文地址:https://www.cnblogs.com/Windeal/p/4284678.html