问题描述
我正在尝试使用 boost 库在 Visual Studio 2019 上创建 3 个执行线程。 3 个线程函数每个都有一个 while(1) 循环,以保持连续执行。
然而,当我执行程序时,我看到只执行了第一个线程(并且命中了一个断点)。 所以我知道第一个线程正在创建,并且执行仍然在第一个函数的 while(1) 循环中,其余的 2 个线程没有执行(断点没有命中)。
使用的部分代码片段如下:
myfunction()
{
// Some code here..
boost::thread t(&myclass::kafkaSvc1ProducerThread,this,rk);
t.join();
boost::thread t2(&myclass::kafkaSvc2ProducerThread,rk);
t2.join();
boost::thread t3(&myclass::kafkaSvc3ProducerThread,rk);
t3.join();
// Some code here..
}
func1(1)
{
while(1)
{
// Some code here...
}
}
void kafkaSvc1ProducerThread()
{
func1();
}
func2(1)
{
while(1)
{
// Some code here...
}
}
void kafkaSvc2ProducerThread()
{
func2();
}
func3(1)
{
while(1)
{
// Some code here...
}
}
void kafkaSvc3ProducerThread()
{
func3();
}
解决方法
只是推迟加入线程:
boost::thread t(&myclass::kafkaSvc1ProducerThread,this,rk);
boost::thread t2(&myclass::kafkaSvc2ProducerThread,rk);
boost::thread t3(&myclass::kafkaSvc3ProducerThread,rk);
t.join();
t2.join();
t3.join();
考虑使用 thread_group
。