-3

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.

KaareZ
  • 615
  • 2
  • 10
  • 22
  • What does "doesn't work" mean? – Kerrek SB Dec 20 '15 at 14:39
  • 1
    `#import`? What is `bar.someMethod`? What error are you getting and what don't you understand about it? What does the `std::thread` documentation/standard say it takes as argument(s)? – Mat Dec 20 '15 at 14:39
  • @Mat How is bar.someMethod relevant? The question is how to use threads when the code is in another object. – KaareZ Dec 20 '15 at 14:43
  • @KaareZ: it matters because it could be a static member function, a non-static member function, or a pointer-to-data-member, all of which are supported and do slightly different things. As you'd have found out by reading the docs. – Mat Dec 20 '15 at 15:04

1 Answers1

1

You want:

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

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

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084