Start thread with member function

前端 未结 5 1341
抹茶落季
抹茶落季 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 05:02

    Some users have already given their answer and explained it very well.

    I would like to add few more things related to thread.

    1. How to work with functor and thread. Please refer to below example.

    2. The thread will make its own copy of the object while passing the object.

      #include
      #include
      #include
      
      using namespace std;
      
      class CB
      {
      
      public:
          CB()
          {
              cout << "this=" << this << endl;
          }
          void operator()();
      };
      
      void CB::operator()()
      {
          cout << "this=" << this << endl;
          for (int i = 0; i < 5; i++)
          {
              cout << "CB()=" << i << endl;
              Sleep(1000);
          }
      }
      
      void main()
      {
          CB obj;     // please note the address of obj.
      
          thread t(obj); // here obj will be passed by value 
                         //i.e. thread will make it own local copy of it.
                          // we can confirm it by matching the address of
                          //object printed in the constructor
                          // and address of the obj printed in the function
      
          t.join();
      }
      

    Another way of achieving the same thing is like:

    void main()
    {
        thread t((CB()));
    
        t.join();
    }
    

    But if you want to pass the object by reference then use the below syntax:

    void main()
    {
        CB obj;
        //thread t(obj);
        thread t(std::ref(obj));
        t.join();
    }
    

提交回复
热议问题