在所有线程未完成时提升线程打印一些东西

Posted

技术标签:

【中文标题】在所有线程未完成时提升线程打印一些东西【英文标题】:boost thread while all thread not completed print something 【发布时间】:2014-03-10 07:19:56 【问题描述】:

需要知道

boost::thread_group tgroup;

循环 10 次

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

tgroup.join_all()

我可以在上面的

【问题讨论】:

【参考方案1】:

您可以使用原子计数器:查看 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

另一种方法是使用信号量

【讨论】:

【参考方案2】:

最简单的方法是在作业“c”结束时打印线程 ID:

void c()

//some code here
some_safe_print << boost::this_thread::get_id();

这样,当线程完成时,最后一条指令就是打印它的 id。

【讨论】:

以上是关于在所有线程未完成时提升线程打印一些东西的主要内容,如果未能解决你的问题,请参考以下文章

IOCP AcceptEx 在连接时未创建完成

延迟线程启动 - 通知所有未唤醒所有线程

Python 3 - 主线程未检测到后台线程中的KeyboardInterrupt,直到用户将鼠标悬停在GUI窗口上

事件后线程未完成

Android Studio 内存泄漏活动未在线程中完成

JavaSE习题 第八章 线程(未完成)