Search code examples
multithreadingc++11stdstdthread

std::thread Run code in object


How can I start a thread executing code from another object/class?

This is what I tried, but didn't work

#import <thread>
#import "Foo.h"

int main() {
    Foo bar;

    std::thread asyncStuff(bar.someMethod);
}

So why doesn't this work, and how can I solve it?

Solution: Call std::thread asyncStuff(&Foo.someMethod, &bar); instead.


Solution

  • You want:

    std::thread asyncStuff(&Foo::someMethod, &bar);
    

    (Don't forget to join or detach the thread before destroying the std::thread object.)