//
// 文件:Producer & Consumer.cpp
//
// 使用原子变量代替互斥锁进行
// 生产者和消费者测试(需要C++11标准支持)
//
#include <atomic>
#include <iostream>
#include <string>
#include <thread>
// 消费者线程
void consumerThread(std::atomic<bool> & ready, std::string & work, std::atomic<bool> & finished) {
// 等待生产者生产完成
for (; ready.load() == false;) {
}
std::cout << work << std::endl;
finished = true; // 标记流程已经执行完成
}
// 生产者线程
void producerThread(std::string & work, std::atomic<bool> & ready) {
work = "done";
ready = true;
}
int main() {
std::atomic<bool> finished(false);
std::atomic<bool> ready(false);
std::string work;
std::thread consumerThreadObject(consumerThread, std::ref(ready), std::ref(work), std::ref(finished));
std::thread producerThreadObject(producerThread, std::ref(work), std::ref(ready));
consumerThreadObject.detach(); // 使消费者线程与其句柄分离
producerThreadObject.detach(); // 使生产者线程与其句柄分离
// 等待执行完成
for (; finished.load() == false;) {
}
return 0;
}