Programing

클래스의 std :: thread 호출 메소드

lottogame 2020. 12. 27. 10:14
반응형

클래스의 std :: thread 호출 메소드


중복 가능성 :
멤버 함수로 스레드 시작

나는 소규모 수업이 있습니다.

class Test
{
public:
  void runMultiThread();
private:
  int calculate(int from, int to);
}  

어떻게 그것의 가능한 방법을 실행하는 calculateparametrs 세트는 서로 다른 두 가지 (예 :와 calculate(0,10), calculate(11,20)방법에서 두 개의 스레드에서) runMultiThread()?

추신 감사합니다 나는 this매개 변수로 패스가 필요하다는 것을 잊었습니다 .


그렇게 어렵지 않습니다.

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

계산 결과가 여전히 필요하면 대신 future를 사용하십시오.

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

참조 URL : https://stackoverflow.com/questions/10998780/stdthread-calling-method-of-class

반응형