Using boost thread and a non-static class function

后端 未结 5 1101
清酒与你
清酒与你 2020-11-30 19:57

So I have done some research, and have found you can create a boost::thread object and have it start with a non-static class function by using \"this\" and boost::bind etc.

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 20:30

    If your object is a functor, i.e. has an operator(), you can pass an instance of it to boost::thread. The operator() does not need to be static. For example:

    #include 
    
    struct th {
        void operator()();
    };
    
    void th::operator()()
    {
        for (;;) {
            // stuff
        }
    }
    
    int main()
    {
        th t;
        boost::thread my_thread( t ); // takes a copy of t !
        my_thread.join(); // blocks
        return 0;
    }
    

提交回复
热议问题