Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start multiple threads without joining

(how) can i start multiple threads like this:

for (i = 0; i < 10; i++) {
   std::thread (myfunction, i, param2, param3);
}

without joining?

like image 496
Niklas Hantke Avatar asked Jan 31 '14 11:01

Niklas Hantke


People also ask

Do you always need to join threads?

no, you can detach one thread if you want it to leave it alone. If you start a thread, either you detach it or you join it before the program ends, otherwise this is undefined behaviour.

What happens if you don't join threads?

If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything.

Why do we need to join threads in C++?

The C++ thread join is used to blocks the threads until the first thread execution process is completed on which particular join() method is called to avoid the misconceptions or errors in the code. If suppose we are not using any join() method in the C++ code.

Can multiple threads run the same function?

There is nothing wrong in calling same function from different threads. If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes, racearound conditions.


2 Answers

Try this

for (int i = 0; i < 10; ++i) {
    std::thread{myfunction, i, param2, param3}.detach();
}

Or if you want to join the threads later, then put them in a std::vector.

std::vector<std::thread> v;
for (int i = 0; i < 10; ++i) {
    v.emplace_back(myfunction, i, param2, param3);
}

// Do something else...

for (auto& t : v) {
    t.join();
}
like image 89
Felix Glas Avatar answered Sep 19 '22 22:09

Felix Glas


Simply don't call join(), detach() instead.

like image 41
Paul Evans Avatar answered Sep 19 '22 22:09

Paul Evans