多线程之信号量--生产消费者问题
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(); }
本文完
相关文章推荐
- java多线程的同步 通信以及生产消费者问题
- Java多线程系列--“基础篇”11之 生产消费者问题
- java多线程的同步 通信以及生产消费者问题
- 生产者消费者问题 这是一个非常经典的多线程题目,题目大意如下:有一个生产者在生产产品,这些产品将提供给若干个消费者去消费,为了使生产者和消费者能并发执行,在两者之间设置一个有多个缓冲区的缓冲池,生产者
- Linux多线程实践(5) --Posix信号量与互斥量解决生产者消费者问题
- java多线程的同步 通信以及生产消费者问题
- java 多线程系列基础篇(十一)之生产消费者问题
- 生产者消费者问题 这是一个非常经典的多线程题目,题目大意如下:有一个生产者在生产产品,这些产品将提供给若干个消费者去消费,为了使生产者和消费者能并发执行,在两者之间设置一个有多个缓冲区的缓冲池,生产者
- Java多线程系列--“基础篇”11之 生产消费者问题 (r)
- 生产者消费者问题 这是一个非常经典的多线程题目,题目大意如下:有一个生产者在生产产品,这些产品将提供给若干个消费者去消费,为了使生产者和消费者能并发执行,在两者之间设置一个有多个缓冲区的缓冲池,生产者
- 多线程“基础篇”11之 生产消费者问题
- POSIX信号量与生产着消费者问题
- Java多线程系列--“基础篇”11之 生产消费者问题
- Java多线程系列--“基础篇”11之 生产消费者问题
- Java多线程系列--“基础篇”11之 生产消费者问题
- Java多线程系列--“基础篇”11之 生产消费者问题
- 进程同步---生产者与消费者问题以及进程同步机制--信号量及P、V操作
- 秒杀多线程第十篇 生产者消费者问题
- 多线程(生产者-消费者问题)
- java多线程之生产者消费者问题