0

I'm certain that this is a simple design error, but I'm not sure where to go with it anyway.

I'd like to spawn a thread from an instance of a class. Specifically:

class Foo
{
    public:
        void bar() { /*do stuff*/ }
};

Usage:

int main()
{
    Foo foo_instance();

    std::thread foo_thread(foo_instance.bar);

    foo_thread.join();

    return 0;
}

When I compile the more detailed version of this, I get invalid use of non-static member function referring to the line std::thread foo_thread(foo_instance.bar);.

So, what am I misunderstanding here? I'd like the object to be initialized and "functional" before I spin it off into a thread, but clearly I'm not using the tools correctly.

pdm
  • 1,027
  • 1
  • 9
  • 24

1 Answers1

1

a member function is not call the same way as a free function because of the implicit this, std::thread need a Callable, this is a little more flexible than just free function.

In you case the simplest is to use a lambda :

std::thread foo_thread( [&] { foo_instance.bar(); } );
galop1n
  • 8,573
  • 22
  • 36
  • Or you can simply give the instance as an argument to the thread ctor `std::thread foo_thread(&Foo::bar, foo_instance);`. – Felix Glas Jan 24 '15 at 00:24
  • it works, but arguments are copied by `std::thread` ctor and you need to use `std::ref` like this `std::thread foo_thread(&Foo::bar, std::ref(foo_instance) );` or the thread will work with a temporary copied `foo_instance` – galop1n Jan 24 '15 at 00:30
  • Yes, and the copy behaviour is created for a reason, it *is* what you want most of the time. Local copies allow you to get around indirection and synchronization troubles etc. But sure, if you want the thread to update an instance in the calling thread then you will need a reference. And synchronization. – Felix Glas Jan 24 '15 at 00:42
  • Thanks very much for the discourse, you two. I tried Snps' solution initially because I understood the syntax much better. However, because the application requires me to interact with the instantiated foo_instance (specifically a file descriptor) the expected result was not produced. So... is that because a lambda refers to the original object's function (and other members) whereas the thread ctor doesn't use the original data? Or is it something else? – pdm Jan 24 '15 at 03:52