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?
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?
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.