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();
}
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
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With