Create thread inside class with function from same class

前端 未结 1 628
南方客
南方客 2020-12-13 00:54

I want to be able to define a class with some data members, and a function which has access to those data members, which are to be private.

I then want a public func

相关标签:
1条回答
  • 2020-12-13 01:34

    foo_func is a (non-static) member function, and it needs an instance of foo on which to operate. This instance must be provided to the thread constructor. If you refer to the std::thread::thread reference page it explains what code is executed in the new thread. The relevant point is that which refers to f being a pointer to member function:

    • If f is pointer to a member function of class T, then it is called. The return value is ignored. Effectively, the following code is executed:
      • (t1.*f)(t2, ..., tN) if the type of t1 is either T, reference to T or reference to type derived from T.
      • ((*t1).*f)(t2, ..., tN) otherwise.

    so it is clear that the instance is required.

    Change to:

    for(...) some_threads.push_back(std::thread(&foo::foo_func, this));
    

    Simple example:

    #include <iostream>
    #include <thread>
    #include <vector>
    
    class foo
    {
    public:
        void make_foo_func_threads()
        {
            for (int i = 0; i < 5; ++i)
                some_threads.push_back(std::thread(&foo::foo_func, this));
            for (auto& t: some_threads) t.join();
        }
    
    private:
        void foo_func() { std::cout << "Hello\n"; }
        std::vector<std::thread> some_threads;
    };
    
    int main()
    {
        foo f;
        f.make_foo_func_threads();
    }
    
    0 讨论(0)
提交回复
热议问题