[英]Waiting loop alternative in c++ thread pool
I have implemented a simple thread pool in my program where the main thread sets the data and notify the threads to execute and then wait in a loop for them to finish.我在我的程序中实现了一个简单的线程池,其中主线程设置数据并通知线程执行,然后在循环中等待它们完成。
while(true){
// set the data
....
// notify threads
...
while(n_done < num_threads){} // wait in the while loop for threads to finish
}
Each thread takes approx 10-15 ms to complete until then the main thread just keeps looping for threads to finish consuming a lot of cpu usage.每个线程大约需要 10-15 毫秒才能完成,直到主线程继续循环线程以完成消耗大量 CPU 使用率。 Is there any alternative method to stop or sleep the main thread execution until the threads complete without a loop.是否有任何替代方法可以停止或休眠主线程执行,直到线程完成而没有循环。
如果您想等待所有线程完成而不重用它们,您可以在最后对每个线程使用join()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.