使用 Boost 打通!
注意:我没有 C++11,所以我将向您展示的代码是用于 C++98 的 Boost libraries。大多数 Boost 内容都以 std::tr1 和随后的标准版本结束,因此其中大部分内容可能无需 Boost 即可转移。
听起来你有多个线程,你不断地但不是一致地分配工作要做。这项工作并不总是需要执行(否则您的线程可以在自己的循环中执行)或者线程可能没有执行它的信息。如果是这种情况,请考虑boost::asio::io_service。
这样,您将需要创建一个始终运行的线程,因此您可能希望将您的线程放在一个类中(尽管您不需要这样做)。
class WorkerThread
{
WorkerThread()
: thread(&WorkerThread::HandleWorkThread, this), io_service(), runThread(true)
{
}
~WorkerThread()
{
// Inform the thread not to run anymore:
runThread = false;
// Wait for the thread to finish:
thread.join();
}
void AssignWork(boost::function<void()> workFunc) { io_service.post(workFunc); }
private:
void HandleWorkThread()
{
while (runThread)
{
// handle work:
io_service.run();
// prepare for more work:
io_service.reset();
}
}
boost::thread thread;
boost::asio::io_service io_service;
bool runThread; // NB: this should be atomic
};
现在您可以拥有以下内容:
void CalculateThings(int, int);
void CalculateThingsComplex(int, int, double);
// Create two threads. The threads will continue to run and wait for work to do
WorkerThread thread1, thread2;
while (true)
{
thread1.AssignWork(boost::bind(&CalculateThings, 20, 30));
thread2.AssignWork(boost::bind(&CalculateThingsComplex, 2, 5, 3.14));
}
您可以根据需要继续分配尽可能多的工作。一旦WorkerThreads 超出范围,它们将停止运行并很好地关闭