在所有线程未完成打印时提升线程
boost thread while all thread not completed print something
需要知道
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。
相关文章:
- 我应该在C++中打印线程 ID 吗?
- 我需要线程函数在不停止实际程序的情况下,每2秒打印一次随机数
- 如何在没有同步的情况下使用多个线程(2、4,8、16 个线程)在循环(10,100、1000 个周期)中打印字符串?
- 线程函数不打印
- 在 C Linux 中使用三个线程使用信号量同步按顺序打印 3 4 5 50 次
- 多线程日志打印先验C
- 为什么奇怪的从带有互斥锁的线程打印
- 如何在多线程 MEX 函数中打印到控制台?
- 在所有线程未完成打印时提升线程
- 当一个线程希望执行或打印某个内容时,如何挂起其他线程
- 多线程程序只适用于打印语句
- 具有多个线程的程序,不打印预期输出
- C++线程意外地打印多次相同的行
- 如何使用 boost.log 以 dec 格式打印进程 ID 和线程 ID
- 中断时提升线程不打印退出消息
- 以线程安全的方式每秒打印队列的当前元素数
- lldb/Xcode:如何打印线程索引、id或名称
- c++ OpenMP每个线程打印私有结构对象
- 如果不使用 pthread_join(),为什么'cout'语句从特定线程打印两次(即使它是同步的)?
- 使用3个线程按顺序打印数字,这些线程打印不同的范围