(how) can i start multiple threads like this:
for (i = 0; i < 10; i++) {
std::thread (myfunction, i, param2, param3);
}
without joining?
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.
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.
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.
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.
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();
}
Simply don't call join()
, detach()
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With