一个简单的信号量的例子

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!\n");
        exit(EXIT_FAILURE);
    }
 
    ret = pthread_create( &a_thread, NULL, thread_function, NULL);
     if (ret != 0) {
        perror( "thread create failed!\n");
        exit(EXIT_FAILURE);
    }
 
    printf( "Enter 'end' to finish!\n");
     while (strncmp( "end", work_area, 3) != 0) {
        fgets(work_area, WORK_SIZE, stdin);
        sem_post( &bin_sem);            // 信号量+ 1 操作
    }
 
    printf( "Waitint for thread join\n");
    ret = pthread_join(a_thread, &thread_result);
     if (ret != 0) {
        perror( "thread_join  failed!\n");
        exit(EXIT_FAILURE);
    }
 
    printf( "thread join()\n");
    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 \n", strlen(work_area) - 1);
        sem_wait( &bin_sem);                   // 信号量- 1 操作
    }
    pthread_exit(NULL);
}
 

 

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值