Linux应用程序:使用信号量实现生产者消费者模型

本文介绍Linux应用编程中的线程同步方法,具体来讲是使用信号量和两个线程实现了一个简单的生产者消费者模型。

#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <semaphore.h>

#define errExit(err, msg) \
	do { errno = err; perror(msg); \
		exit(EXIT_FAILURE); } while(0)

sem_t consumer_ready;
sem_t producer_ready;
int count;

void *__producer_thread_func(void *arg)
{
	char *name = "producer";
	int ret;
	ret = prctl(PR_SET_NAME, (unsigned long)name, NULL, NULL, NULL);
	if(ret < 0) {
		perror("prctl PR_SET_NAME");
		exit(EXIT_FAILURE);
	}
	count = 0;
	while(1) {
		sem_wait(&consumer_ready);
		sleep(1);
		count++;
		printf("producer: %d\n", count);
		sem_post(&producer_ready);
	}
}

void *__consumer_thread_func(void *arg)
{
        char *name = "consumer";
        int ret;
        ret = prctl(PR_SET_NAME, (unsigned long)name, NULL, NULL, NULL);
        if(ret < 0) {
                perror("prctl PR_SET_NAME");
                exit(EXIT_FAILURE);
        }
        while(1) {
                sem_wait(&producer_ready);
		count--;
                printf("consumer: %d\n", count);
                sem_post(&consumer_ready);
        }
}

int main()
{
	pthread_t thread_producer;
	pthread_t thread_consumer;
	int ret;
	
	ret = sem_init(&producer_ready, 0, 0);
	if(ret < 0) {
		perror("sem producer_ready");
		return -1;
	}
	ret = sem_init(&consumer_ready, 0, 1);
	if(ret < 0) {
		perror("sem consumer_ready");
		return -1;
	}

	ret = pthread_create(&thread_producer, NULL, __producer_thread_func, NULL);
	if(ret) {
		errExit(ret, "create producer");
	}

	ret = pthread_create(&thread_consumer, NULL, __consumer_thread_func, NULL);
	if(ret) {
		errExit(ret, "create consumer");
	}


	pthread_join(thread_producer, NULL);
	pthread_join(thread_consumer, NULL);
	printf("test end\n");
	return 0;
}

上面的程序中,生产者每一秒钟将count加1,消费者将count减1

运行的结果是生产者打印1,消费者打印0.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值