pthread function from a class

前端 未结 9 1060
天命终不由人
天命终不由人 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:41

    This is a bit old question but a very common issue which many face. Following is a simple and elegant way to handle this by using std::thread

    #include 
    #include 
    #include 
    #include 
    
    class foo
    {
        public:
            void bar(int j)
            {
                n = j;
                for (int i = 0; i < 5; ++i) {
                    std::cout << "Child thread executing\n";
                    ++n;
                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
                }
            }
            int n = 0;
    };
    
    int main()
    {
        int n = 5;
        foo f;
        std::thread class_thread(&foo::bar, &f, n); // t5 runs foo::bar() on object f
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
        std::cout << "Main Thread running as usual";
        class_thread.join();
        std::cout << "Final value of foo::n is " << f.n << '\n';
    }
    

    Above code also takes care of passing argument to the thread function.

    Refer std::thread document for more details.

提交回复
热议问题