我正在使用C++ 11上的线程库来做一些事情。问题是我的线程数量有限(4)。几个线程的多个任务
我会知道如何对付它:
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#define NUMBER_OF_THREADS 4
void foo(const std::string& astring)
{
std::cout << astring << std::endl;
}
int main()
{
std::vector<std::string> list_of_strings(100);
// values assigned
std::vector<std::thread> list_of_threads(NUMBER_OF_THREADS);
for(std::vector<std::string>::const_iterator it_string = list_of_strings.begin() ; it_string != list_of_strings.end() ; ++it_string)
{
bool check = false;
unsigned int = 0;
while(!check) // loop which assigns the next task to the first thread ready.
{
if(check = list_of_threads.at(i).ISFREE()) // how to do ?
{
list_of_threads.at(i) = thread(&foo,*it_string);
}
else
{
i = (i + 1) % NUMBER_OF_THREADS;
}
}
}
for(std::vector<std::thread>::iterator it = list_of_threads.begin() ; it != list_of_threads.end() ; ++it)
it->join(); // the main thread is waiting for all threads before closing.
return 0;
}
但我不知道如何检查,如果线程准备一个新的任务或没有。任何想法 ?
德鲁霍尔迄今为止已是最好的答案。忘记使用一些令人讨厌的(并且很可能是bug),“线程管理器循环”来显式管理线程,并将任务排队到池中。 –
@BradTilley:是的,我在我的代码中使用它,我只是在我的问题中编写了#define,因为它更明显:p – Alfred