How to create a thread inside a class function?

前端 未结 2 2179
迷失自我
迷失自我 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:47

    #include 
    #include 
    #include 
    
    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();
    }
    

提交回复
热议问题