Posts Producer and Consumer
Post
Cancel

Producer and Consumer

生产者和消费者问题

经典同步问题,生产者进程和消费者进程共享一块缓冲区,生产者向缓冲区写入数据,消费者消耗缓冲区的数据;

同步事项

  • 生产者写入时消费者不能消耗
  • 消费者消耗时生产者不能写入
  • 生产者在缓冲区满时不能再写入
  • 消费者在缓冲区空时不能再消耗

代码环境 :

  • 基于C++ 11的线程库和并发库
  • VS2017

使用信号量empty(记录多少空位),条件变量full(记录多少满位),条件变量mutex(实现互斥)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <queue>
#include <thread>             
#include <mutex>
#include <Windows.h>
#include <condition_variable> 

#define MAX_SIZE 20; 

std::mutex Mutex;
std::condition_variable empty;
std::condition_variable full;

std::queue<int> Queue;

void _consumer() {
	do {
		std::unique_lock<std::mutex> lck(Mutex);
		empty.wait(lck, [] {return Queue.size() != 0; });

		Queue.pop();
		std::cout << "consumer consume one item: "
			<< "Queue size is " << Queue.size() << std::endl;
		Sleep(100);

		full.notify_one();
	} while (1);
}

void _producer() {
	do {
		std::unique_lock<std::mutex> lpk(Mutex);
		full.wait(lpk, [] {return Queue.size() != MAX_SIZE; });

		Queue.push(rand());
		std::cout << "produce produce one item"
			<< "Queue size is " << Queue.size() << std::endl;
		Sleep(100);

		empty.notify_one();
	} while (1);
}

int main(int argc, char** argv) {
	auto c = std::thread(_consumer);
	auto p = std::thread(_producer);
	p.join();
	c.join();
	return 0;
}
OLDER POST NEWER POST

Comments powered by Disqus.

Search Results