如何在cpp中使用线程来实现来自两个不同类的两个方法的并行执行



因此,我一直在尝试使用std::thread对象来启用在另一个类的方法执行期间执行另一个类别方法。伪代码如下所示。

class A (init_A_args ){
 A::method1(args_method1) {
   method1 functionality;
   return;  
}
 A::callback_method2(args_method2) {
   method2 functionality; 
   return; 
}
}
class B (init_B_args){
 B::method1(args_B_method1) {
    method1 functionality;
    return; 
}
 B::method2(args_B_method2)
    method2 functionality; 
    return; 
}

所以我想做的事情如下:

A::callback_method2(args_method2) {
   init class B; 
   for (condition){
       classB.method2(); // should call this method periodically but in such way that it doesn't
       ...;             // block execution of rest of the for loop
       rest-of-the-for-loop; 
       ...; 
   }
   classB.stop(); 
   return; 
}

我不知道该怎么做,但我确信我需要使用线程。我可以在A类回调方法中实例化类B,但是,在调用classB.method2((之后;循环停止,并且在classB.method2()中继续执行。因此,classB.method2()在类A的回调方法中阻塞for循环。然而,我想执行classB.method2(),但在A::callback_method2中继续执行for循环。在脱离A::callback_method2的范围后,B类应停止并销毁。所以我想优雅地在类A和实例化类B中的回调方法的执行之间切换,例如它的方法2
我一直在尝试使用std::thread,但运气不好,我可能做错了什么。因此,为了澄清,A::callback_method2应该实例化类B并定期调用B.method2(),同时继续执行for循环,因此B.method2将在后台运行,而for循环正常执行。我有main函数,但它应该只实例化类A,然后再实例化类B,所以我不确定这与我的问题语句有什么关系(因为我主要在主要方法中看到了thread.join()thread.detach()的内容。

您可以为std::thread对象提供一个可调用对象(可以调用的对象(,线程对象将运行该可调用对象。如果你不想让线程阻塞执行,你应该detach线程,这样它就变成了一个守护进程线程,这意味着它在后台运行,而不会阻塞执行的主线程。在使用此解决方案时,您应该考虑在线程上运行可调用程序的副作用:如果它不影响其范围之外的变量/状态,则无需担心太多,但如果影响了,则需要注意线程安全:必须考虑对变量的并发访问。

#include <iostream>
#include <thread>
using namespace std;
void method1()
{
    long long j = 0;
    for(int i = 0; i < 10000; ++i)
    {
        j += i;
    }
    cout << "Sum is: " << j << endl;
}
int main()
{
    thread t1(method1);
    t1.detach();
    cout << "Stuff on main thread." << endl;
    return 0;
}

最新更新