在所有线程未完成打印时提升线程

boost thread while all thread not completed print something

本文关键字:线程 打印 未完成      更新时间:2023-10-16

需要知道

boost::thread_group tgroup;

循环10次

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

< ==

tgroup.join_all()

我在上面的位置可以做什么,以连续打印完成工作的线程数

您可以使用原子计数器:在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 << " runningn";
        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"结束时打印线程ID:

void c()
{
//some code here
some_safe_print << boost::this_thread::get_id();
}

这样,当线程完成时,最后一个指令是打印其ID。