Start thread with member function

前端 未结 5 1350
抹茶落季
抹茶落季 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:59

    @hop5 and @RnMss suggested to use C++11 lambdas, but if you deal with pointers, you can use them directly:

    #include 
    #include 
    
    class CFoo {
      public:
        int m_i = 0;
        void bar() {
          ++m_i;
        }
    };
    
    int main() {
      CFoo foo;
      std::thread t1(&CFoo::bar, &foo);
      t1.join();
      std::thread t2(&CFoo::bar, &foo);
      t2.join();
      std::cout << foo.m_i << std::endl;
      return 0;
    }
    

    outputs

    2
    

    Rewritten sample from this answer would be then:

    #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(&Wrapper::member1, this);
          }
          std::thread member2Thread(const char *arg1, unsigned arg2) {
              return std::thread(&Wrapper::member2, this, arg1, arg2);
          }
    };
    
    int main() {
      Wrapper *w = new Wrapper();
      std::thread tw1 = w->member1Thread();
      tw1.join();
      std::thread tw2 = w->member2Thread("hello", 100);
      tw2.join();
      return 0;
    }
    

提交回复
热议问题