Best way to start a thread as a member of a C++ class?

前端 未结 5 1151
一整个雨季
一整个雨季 2020-12-05 05:33

I\'m wondering the best way to start a pthread that is a member of a C++ class? My own approach follows as an answer...

5条回答
  •  抹茶落季
    2020-12-05 05:56

    This can be simply done by using the boost library, like this:

    #include 
    
    // define class to model or control a particular kind of widget
    class cWidget
    {
    public:
    void Run();
    }
    
    // construct an instance of the widget modeller or controller
    cWidget theWidget;
    
    // start new thread by invoking method run on theWidget instance
    
    boost::thread* pThread = new boost::thread(
        &cWidget::Run,      // pointer to member function to execute in thread
        &theWidget);        // pointer to instance of class
    

    Notes:

    • This uses an ordinary class member function. There is no need to add extra, static members which confuse your class interface
    • Just include boost/thread.hpp in the source file where you start the thread. If you are just starting with boost, all the rest of that large and intimidating package can be ignored.

    In C++11 you can do the same but without boost

    // define class to model or control a particular kind of widget
    class cWidget
    {
    public:
    void Run();
    }
    
    // construct an instance of the widget modeller or controller
    cWidget theWidget;
    
    // start new thread by invoking method run on theWidget instance
    
    std::thread * pThread = new std::thread(
        &cWidget::Run,      // pointer to member function to execute in thread
        &theWidget);        // pointer to instance of class
    

提交回复
热议问题