gpt4 book ai didi

c++ - 在所有线程未完成时 boost 线程打印一些东西

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:32 26 4
gpt4 key购买 nike

需要知道

boost::thread_group tgroup;

循环10次

tgroup.create_thread( boost::bind( &c , 2, 2, ) )

<==

tgroup.join_all()

我可以在上面的 <== 位置做什么来连续打印完成那里作业的线程数

最佳答案

您可以使用原子计数器:参见 Live On Coliru

#include <boost/thread/thread.hpp>
#include <boost/atomic.hpp>

static boost::atomic_int running_count(20);

static void worker(boost::chrono::milliseconds effort)
{
boost::this_thread::sleep_for(effort);
--running_count;
}

int main()
{
boost::thread_group tg;

for (int i = 0, count = running_count; i < count; ++i) // count protects against data race!
tg.create_thread(boost::bind(worker, boost::chrono::milliseconds(i*50)));

while (running_count > 0)
{
std::cout << "Monitoring threads: " << running_count << " running\n";
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
}

tg.join_all();
}

示例输出:

Monitoring threads: 19 running
Monitoring threads: 17 running
Monitoring threads: 15 running
Monitoring threads: 13 running
Monitoring threads: 11 running
Monitoring threads: 9 running
Monitoring threads: 7 running
Monitoring threads: 5 running
Monitoring threads: 3 running
Monitoring threads: 1 running

另一种方法是使用信号量

关于c++ - 在所有线程未完成时 boost 线程打印一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22294212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com