我的程序通过使用空闲的工作线程将多行文本打印到控制台。然而,问题是工作线程在打印文本之前没有等待前一个工作线程完成,这导致文本被插入到另一个工作线程的文本中,如下图所示:
我需要通过使用 std::condition_variable 来解决这个问题——称为忙等待问题。我已经尝试在下面的代码中实现 condition_variable,基于在这个链接上找到的例子,下面的 stackoverflow 问题对我有帮助,但还不够,因为我对 C++ 的一般知识有限。所以最后我只是把所有的东西都注释掉了,我现在不知所措。
// threadpool.cpp
// Compile with:
// g++ -std=c++11 -pthread threadpool.cpp -o threadpool
#include <thread>
#include <mutex>
#include <iostream>
#include <vector>
#include <deque>
class ThreadPool; // forward declare
//std::condition_variable cv;
//bool ready = false;
//bool processed = false;
class Worker {
public:
Worker(ThreadPool &s) : pool(s) { }
void operator()();
private:
ThreadPool &pool;
};
class ThreadPool {
public:
ThreadPool(size_t threads);
template<class F> void enqueue(F f);
~ThreadPool(); …
Run Code Online (Sandbox Code Playgroud)