0

I have a basic producer/consumer application where some workers go and perform a task on a shared problem. It's not trivial enough to use a concurrent for or something similar. I've gotten used to using Qt for threading because it makes it very easy to do things like this:

for(int i = 0; i < nworkers; i++){
    Worker* myworker = new Worker();
    QThread* thread = new QThread;
    myworker->attachToThread(thread);

    myworker->doSomething(someArgument);
    myworker->doSomethingElse(someOtherArgument);
    myworker->run();
}

I'd like to try and switch to using std::thread partially for the learning exercise and partially so that I don't need to link in Qt. So my question is, is there a straightforward way to spin off an object in a thread and then call functions from it? The model above works very well in this case. To be honest for my application I can get away with using std::async and passing everything as arguments to the worker function, but I was curious if there were a way to write the above code in terms of the standard library instead.

I guess I can do something like

void foo(someArguments){
    Worker* myworker = new Worker();
    myworker->doSomething(someArguments);
    myworker->run();
}

and thread that, but then everything is encapsulated inside foo. With Qt I'd have access to that threaded object anywhere it's in scope.

I understand the basics of running a function in another thread with the standard library, but I wondered if what I want is something that's only possible with the help of a larger framework?

Josh
  • 2,658
  • 31
  • 36

1 Answers1

0

You want to run class method as a thread function?

std::thread t(&Worker::run, myworker, arg1, arg2, ...);
t.join();

or maybe make Worker method

Worker::runT() {
  doSomething();
  doMore();
  std::thread t(&Worker::run, this);
}

you could put .join() somewhere, or in destructor

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64