C++BOOST实现主线程生成两个子线程,读取缓冲区信息后将缓冲区清空,一个线程的两次显示操作之间可以加入适当的时延以便于观察
时间: 2024-05-27 16:14:36 浏览: 95
#include <boost/thread.hpp>
#include <iostream>
#include <queue>
#include <string>
boost::mutex mutex; // 互斥锁
std::queue<std::string> buffer; // 缓冲区
void producer() {
for (int i = 1; i <= 10; ++i) {
std::string message = "Message " + std::to_string(i);
mutex.lock(); // 加锁
buffer.push(message);
std::cout << "Produced: " << message << std::endl;
mutex.unlock(); // 解锁
boost::this_thread::sleep_for(boost::chrono::milliseconds(500)); // 线程休眠500毫秒
}
}
void consumer1() {
while (true) {
mutex.lock(); // 加锁
if (!buffer.empty()) {
std::string message = buffer.front();
buffer.pop();
std::cout << "Consumer 1 consumed: " << message << std::endl;
}
mutex.unlock(); // 解锁
if (buffer.empty()) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(1000)); // 线程休眠1秒
}
}
}
void consumer2() {
while (true) {
mutex.lock(); // 加锁
if (!buffer.empty()) {
std::string message = buffer.front();
buffer.pop();
std::cout << "Consumer 2 consumed: " << message << std::endl;
}
mutex.unlock(); // 解锁
if (buffer.empty()) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(1000)); // 线程休眠1秒
}
}
}
int main() {
boost::thread producerThread(producer);
boost::thread consumerThread1(consumer1);
boost::thread consumerThread2(consumer2);
producerThread.join();
consumerThread1.join();
consumerThread2.join();
return 0;
}
阅读全文