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

来源:互联网 发布:linux 嵌入式编程 编辑:程序博客网 时间:2024/05/21 06:50

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

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

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

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

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

代码:

/* * pro_cus.cpp * *      Author: casa */#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h>#include <semaphore.h>#define BUF_SIZE 5int 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();}

本文完
0 0
原创粉丝点击