How to create a thread inside a class function?

前端 未结 2 2143
迷失自我
迷失自我 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条回答
  • 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.

    0 讨论(0)
  • 2021-02-09 16:47
    #include <thread>
    #include <string>
    #include <iostream>
    
    class Class
    {
    public:
        Class(const std::string& s) : m_data(s) { }
        ~Class() { m_thread.join(); }
        void runThread() { m_thread = std::thread(&Class::print, this); }
    
    private:
        std::string m_data;
        std::thread m_thread;
        void print() const { std::cout << m_data << '\n'; }
    };
    
    int main()
    {
        Class c("Hello, world!");
        c.runThread();
    }
    
    0 讨论(0)
提交回复
热议问题