我有以下内容for
loop:
for (int i = 0; i < 100; i++) {
someJob();
}
我只想用 5 个线程运行这个函数,我该怎么做?
我无法使用任何外部库。
我尝试过创建一个包含 5 个线程的数组,如果索引等于 5,则等待所有线程并再次执行此操作,但我确信还有另一种方法可以做到这一点:
std::thread t[THREAD_COUNT];
int j=0;
for (int i = 0; i < 100; i++) {
t[j++] = std::thread(someJob);
if (j == THREAD_COUNT)
{
for (int k = 0; k < THREAD_COUNT; k++)
{
if (t[k].joinable())
t[k].join();
}
j = 0;
}
}
有什么建议吗? (我无法使用增强)
Thanks!
您可以创建一个函数来测试您的线程数组,以找到一个空闲线程来运行每个连续的作业。像这样的事情:
// synchronized output to prevent interleaving of results
#define sync_out(m) do{std::ostringstream o; o << m << '\n'; std::cout << o.str();}while(0)
void someJob(int id)
{
sync_out("thread: " << id);
}
template<typename Job>
void start_thread(std::vector<std::thread>& threads, Job&& job)
{
// find an ended thread
for(auto&& thread: threads)
{
if(thread.joinable()) // still running or waiting to join
continue;
thread = std::thread(job);
return;
}
// if not wait for one
for(auto&& thread: threads)
{
if(!thread.joinable()) // dead thread (not run or already joined)
continue;
thread.join();
thread = std::thread(job);
return;
}
}
int main()
{
std::vector<std::thread> threads(5); // 5 threads
for(int i = 0; i < 100; i++)
start_thread(threads, [=]{someJob(i);});
// wait for any unfinished threads
for(auto&& thread: threads)
if(thread.joinable())
thread.join();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)