我有一个算法需要很长时间才能运行(数小时到数天),并且循环次数很多。
我想尽可能使用std :: thread库作为C ++ 11的一部分。
我想启动nTread工作线程,然后让它们处于空闲状态,直到指示执行“taskNumber”操作。
我可以用未来和承诺做到这一点吗?
有更好的方法吗?
在下面的代码中,我要做的是:
我正在尝试的内容如下:
#include <iostream>
#include <thread>
#include <future>
#include <vector>
std::vector<std::promise<int>> readyPromise;
std::vector<std::promise<bool>> donePromise;
void initiazer(int threadNumber)
{
while (true) {
// Wait to see if it is ready to run
std::future<int> readyFuture = readyPromise[threadNumber].get_future();
int taskNumber = readyFuture.get();
std::cout<<"Inside Thread: " << threadNumber << " doing task: " << taskNumber << std::endl;
// tell it that this is done
donePromise[threadNumber].set_value(true);
if (taskNumber == 9)
exit(0);
}
}
int main()
{
int nThread = 6;
// Create the promises and future
std::vector<std::future<bool>> doneFuture;
for (int i=0; i<=nThread; ++i) {
readyPromise.push_back(std::promise<int>());
donePromise.push_back(std::promise<bool>());
doneFuture.push_back(std::future<bool>());
}
// Create the threads
std::vector<std::thread> threads;
std::cout << "Create nThread threads" << std::endl;
for (int i=0; i<=nThread; ++i)
threads.push_back(std::thread(initiazer, i));
// Loop 100 times
for (int j=0; j<100; j++) {
for (int task=0; task<4; j++) {
// tell the threads to go
for (int i=0; i<nThread; i++) {
doneFuture[i] = donePromise[nThread].get_future();
readyPromise[i].set_value(task);
}
// Nothing happening here.
// Wait for the threads to finish
for (int i=0; i<nThread; i++) {
doneFuture[i].get();
}
// Do some work on the main thread.
}
}
int task = 9; // Tell threads to exit
for (int i=0; i<nThread; i++) {
doneFuture[i] = donePromise[nThread].get_future();
readyPromise[i].set_value(task);
}
// Wait for all the threads to exit.
for (int i=0; i<nThread; i++) {
threads[i].join();
}
return 0;
}