Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launching std::thread using shared_ptr

When you construct a new thread the supplied function object is copied into the storage belonging to the newly created thread. I want to execute an object method in a new thread. The object should not be copied. So I pass shared_ptr of the object to std::thread constructor. How can I launch a new thread with std::shared_ptr() object? 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();     
}
like image 744
Alexey Avatar asked Sep 18 '15 15:09

Alexey


2 Answers

You overcomplicate the issue, just pass std::shared_ptr itself, std::bind and std::thread know how to deal with it:

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

This way std::thread instance will share ownership and that would guarantee object would not be destroyed before myThread

like image 180
Slava Avatar answered Sep 23 '22 04:09

Slava


You have a lot of errors in you sketch code. I think a more readable way would be to use a lambda that captures the sptr by value and then deferences it to call the function.

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

It is not perfectly clear what you want to do. If you want to launch a new thread that runs a member function without copying the class instance the syntax would be one of those:

Foo foo;
std::thread th1(&Foo::moo, &foo);
std::thread th2([&]{ foo.moo(); });
like image 35
typ1232 Avatar answered Sep 23 '22 04:09

typ1232