Running std :: thread using shared_ptr

When you create a new thread, the supplied function object is copied to the repository that belongs to the newly created thread. I want to execute an object method in a new thread. The object cannot be copied. Therefore, I pass the shared_ptrobject to the constructor std::thread. How can I start a new thread with an object std::shared_ptr()? for example

class Foo {
public: 
    void operator()() {       
        // do something
    }    
};

int main() {
    std::shared_ptr<Foo> foo_ptr(new Foo);

    // I want to launch a foo_ptr() in a new thread
    // Is this the correct way?
    std::thread myThread(&Foo::operator(), foo_ptr.get());  
    myThread.join();     
}
+4
source share
2 answers

You overcome the problem, just pass it along std::shared_ptr, std::bindand std::threadhow to deal with it:

std::thread myThread( &Foo::operator(), foo_ptr );  

Thus, the instance std::threadwill share the property and ensure that the object will not be destroyed beforemyThread

+8

. , , sptr , , .

#include <thread>
#include <memory>
#include <cstdio>

class Foo
{
public:
    void operator()()
    {
        printf("do something\n");
    }
};

int main()
{
    auto foo_ptr = std::make_shared<Foo>();

    std::thread myThread([foo_ptr] { (*foo_ptr)(); });
    myThread.join();
}

, . , - , :

Foo foo;
std::thread th1(&Foo::moo, &foo);
std::thread th2([&]{ foo.moo(); });
+5

Source: https://habr.com/ru/post/1608049/


All Articles