How to create a thread inside a class function?

前端 未结 2 2144
迷失自我
迷失自我 2021-02-09 16:17

I am very new to C++.

I have a class, and I want to create a thread inside a class\'s function. And that thread(function) will call and access the class function and va

2条回答
  •  -上瘾入骨i
    2021-02-09 16:43

    You can pass a static member function to a pthread, and an instance of an object as its argument. The idiom goes something like this:

    class Parallel
    {
    private:
        pthread_t thread;
    
        static void * staticEntryPoint(void * c);
        void entryPoint();
    
    public:
        void start();
    };
    
    void Parallel::start()
    {
        pthread_create(&thread, NULL, Parallel::staticEntryPoint, this);
    }
    
    void * Parallel::staticEntryPoint(void * c)
    {
        ((Parallel *) c)->entryPoint();
        return NULL;
    }
    
    void Parallel::entryPoint()
    {
        // thread body
    }
    

    This is a pthread example. You can probably adapt it to use a std::thread without much difficulty.

提交回复
热议问题