如何使用 C++ 中的 boost 库在 Visual Studio 2019 中创建 3 个并行执行线程?

问题描述

我正在尝试使用 boost 库在 Visual Studio 2019 上创建 3 个执行线程。 3 个线程函数每个都有一个 while(1) 循环,以保持连续执行。

然而,当我执行程序时,我看到只执行了第一个线程(并且命中了一个断点)。 所以我知道第一个线程正在创建,并且执行仍然在第一个函数的 while(1) 循环中,其余的 2 个线程没有执行(断点没有命中)。

在这种情况下,我该如何修改代码,让所有 3 个线程都运行?

使用的部分代码片段如下:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...