-1

I have a simple class lets call it worker

class Worker{
  Worker(){
    // Initialize
  }
  void runWorker(){
     while(1){ 
        //Do work
     }
  }
}

What is the correct C++ way to initialize and run thing class on a new thread?

Iliketoproveit
  • 445
  • 6
  • 15
  • Possible duplicate of [Simple example of threading in C++](https://stackoverflow.com/questions/266168/simple-example-of-threading-in-c) – tambre Apr 07 '18 at 15:16
  • @tambre Im more interested in the C++ way to design multithreaded objects. That question has a function that is then run on a new thread. In my case, I have a class that I want to run in a new thread – Iliketoproveit Apr 07 '18 at 15:18
  • 2
    "I have a class that I want to run in a new thread" - One does not run classes. One runs *functions*. – Jesper Juhl Apr 07 '18 at 15:33
  • okay... I have a member function that I want to run. This member function will be modifying private members of my class. Is there a standard way to do this in C++? – Iliketoproveit Apr 07 '18 at 15:38

1 Answers1

3

If you're using C++11 or later, threads are built in.

std::thread t([]() {
    Worker w; // construct as normal
    w.runWorker();
};

If you want to use the same Worker in multiple threads, you can construct it outside your thread and capture it in the lambda.

Worker w;
std::thread t1([&w]() {
    w.runWorker();
});
std::thread t2([&w]() {
    w.runWorker();
});

If you use the latter method, make sure w doesn't go out of scope since it's capturing by reference.

Stephen Newell
  • 7,330
  • 1
  • 24
  • 28
  • Is there a way to do this using C++98? – Iliketoproveit Apr 07 '18 at 15:16
  • 2
    Not using standard C++. – Stephen Newell Apr 07 '18 at 15:18
  • The standard didn't add `` until C++11, for code before that you'd have to use something like `boost::thread` or `pthread` – Cory Kramer Apr 07 '18 at 15:18
  • wow, seems like a basic thing to have can't believe it wasnt added until much later – Iliketoproveit Apr 07 '18 at 15:19
  • @Iliketoproveit • there were non-standard (in the context of the C++ language standard), non-very-portable (often platform specific) implementations prior to C++11. – Eljay Apr 07 '18 at 15:33
  • 2
    @Iliketoproveit C++ is a very big umbrella. Some of the systems beneath it didn't (and still don't) have threads. Requiring compiler developers to implement threading support on these systems would likely have added C++ to the junk heap of compilers only used by academics. – user4581301 Apr 07 '18 at 15:38
  • If you call `runWorker` on an object shared between threads, it should be declared `const` – LWimsey Apr 07 '18 at 15:46