Start thread with member function

前端 未结 5 1340
抹茶落季
抹茶落季 2020-11-21 04:31

I am trying to construct a std::thread with a member function that takes no arguments and returns void. I can\'t figure out any syntax that works -

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 04:52

    Here is a complete example

    #include 
    #include 
    
    class Wrapper {
       public:
          void member1() {
              std::cout << "i am member1" << std::endl;
          }
          void member2(const char *arg1, unsigned arg2) {
              std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
          }
          std::thread member1Thread() {
              return std::thread([=] { member1(); });
          }
          std::thread member2Thread(const char *arg1, unsigned arg2) {
              return std::thread([=] { member2(arg1, arg2); });
          }
    };
    int main(int argc, char **argv) {
       Wrapper *w = new Wrapper();
       std::thread tw1 = w->member1Thread();
       std::thread tw2 = w->member2Thread("hello", 100);
       tw1.join();
       tw2.join();
       return 0;
    }
    

    Compiling with g++ produces the following result

    g++ -Wall -std=c++11 hello.cc -o hello -pthread
    
    i am member1
    i am member2 and my first arg is (hello) and second arg is (100)
    

提交回复
热议问题