pthread function from a class

前端 未结 9 1068
天命终不由人
天命终不由人 2020-11-22 01:00

Let\'s say I have a class such as

class c { 
    // ...
    void *print(void *){ cout << \"Hello\"; }
}

And then I have a vector of c

9条回答
  •  广开言路
    2020-11-22 01:35

    My favorite way to handle a thread is to encapsulate it inside a C++ object. Here's an example:

    class MyThreadClass
    {
    public:
       MyThreadClass() {/* empty */}
       virtual ~MyThreadClass() {/* empty */}
    
       /** Returns true if the thread was successfully started, false if there was an error starting the thread */
       bool StartInternalThread()
       {
          return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
       }
    
       /** Will not return until the internal thread has exited. */
       void WaitForInternalThreadToExit()
       {
          (void) pthread_join(_thread, NULL);
       }
    
    protected:
       /** Implement this method in your subclass with the code you want your thread to run. */
       virtual void InternalThreadEntry() = 0;
    
    private:
       static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}
    
       pthread_t _thread;
    };
    

    To use it, you would just create a subclass of MyThreadClass with the InternalThreadEntry() method implemented to contain your thread's event loop. You'd need to call WaitForInternalThreadToExit() on the thread object before deleting the thread object, of course (and have some mechanism to make sure the thread actually exits, otherwise WaitForInternalThreadToExit() would never return)

提交回复
热议问题