提问者:小点点

如何在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()之后;for循环停止,在classb.method2()中继续执行。因此classb.method2()阻止类A的回调方法中的for循环。然而,我希望执行classb.method2()但继续执行A::callback_method2中的for循环。在超出A::Callback_Method2的范围后,应停止并销毁类B。因此,我想在类A和实例化的类B(例如method2)中优雅地切换回调方法的执行。
我一直在尝试使用std::thread,但运气不好,我可能做错了什么。因此,为了澄清,A::Callback_Method2应该实例化类B,并定期调用B.Method2(),同时继续for循环执行,这样B.Method2将在后台运行,而for循环正常执行。我有main函数,但它应该只实例化类A,然后类又实例化B,所以我不确定这与我的问题语句有什么关系(因为我主要在main方法中看到了thread.join()thread.detach()


共1个答案

匿名用户

您可以为std::thread对象提供一个可调用对象(可以调用的东西),并且thread对象将运行该可调用对象。如果您不希望线程阻塞执行,您应该分离线程,这样它就变成了一个守护进程线程,这意味着它在后台运行,而不阻塞执行的主线程。在使用这个解决方案时,您应该考虑线程上的可调用运行的副作用:如果它不影响其作用域之外的变量/状态,您就不需要担心太多,但是如果它影响了,您就需要注意线程的安全性:必须查看对变量的并发访问。

#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;
}