您的位置:首页 > 其它

多线程之信号量--生产消费者问题

2014-04-22 23:35 246 查看
在诸如生产者消费者问题中,信号量被广泛使用,前段时间网上流传的奶茶京东的例子,就是一个信号量的问题。

下面以生产者消费者问题为例,说一下信号量和锁的结合应用:

一般有两个信号量:对于生产者的缓冲区可用资源数目和对于消费者的产品可用的资源数目。

一般有两个函数指针:生产者函数指针在生产,消费者函数指针在消费。

这个两个函数指针指向的函数中如果是多线程情况会有锁来避免多个线程修改缓冲区。

代码:

/*
* pro_cus.cpp
*
*      Author: casa
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#define BUF_SIZE 5

int in, out;
int buf[BUF_SIZE];

pthread_mutex_t mutex;   ///生产者与消费者互斥访问缓冲区
sem_t empty;             ///缓冲区可用资源数,对于生产者
sem_t full;              ///产品可用资源数,对于消费者

void *producer(void *arg) {
int i;
for (i=1; i<=20; i++) {
sem_wait(&empty);
pthread_mutex_lock(&mutex);
in = (in + 1) % BUF_SIZE;
buf[in] = i;
printf("produce %d\n", buf[in]);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
return NULL;
}

void *customer(void *arg) {
int i;
for (i=1; i<=20; i++) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
out = (out + 1) % BUF_SIZE;
printf("customer %d\n", buf[out]);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
return NULL;
}

int producer_consumer(void) {
pthread_t tid_prod, tid_cust;

in = out = -1;
sem_init(&empty, 0, BUF_SIZE);   ///初始化为BUF_SIZE个缓冲可用
sem_init(&full, 0, 0);           ///初始化为不可用
pthread_mutex_init(&mutex, NULL);

if (pthread_create(&tid_prod, NULL, producer, NULL) != 0) {
perror("create producer pthread error!\n");
exit(1);
}

if (pthread_create(&tid_cust, NULL, customer, NULL) != 0) {
perror("create customer pthread error!\n");
exit(1);
}

if (pthread_join(tid_prod, NULL) != 0) {
perror("join producer pthread error!\n");
exit(1);
}

if (pthread_join(tid_cust, NULL) != 0) {
perror("join customer pthread error!\n");
exit(1);
}

pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);

return 0;
}


测试代码:

void test_pc(){
producer_consumer();
}


本文完
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐