I am new to multithreading so any suggestions would be appreciated. The following program takes in a vector of integers(eg. 1 2 3 4 5 6 7) and processes each of them as threads. I was wondering if the method with which I join the threads is correct, and if I can make any improvements.
I hope my explanation is clear! Here is my code snippet. It's not the complete code, I'm just ensuring I'm going the right way:
//vector's name is 'inputs' and it contains integers
for (int unsigned i = 0; i < inputs.size(); i++) {
thread thread_obj(thread_function, inputs.at(i));
thread_obj.detach();
}
for (int unsigned i = 0; i < inputs.size(); i++) {
thread_obj.join();
}
Your code has undefined behavior so no, it is not correct. The issue here is that you can only call join()
if joinable()
is true
and because you called detach()
, joinable()
will return false
.
The good news is it is really quite a simple fix. You just need to remove the call to detach
. To complete out the code just populate a vector of threads and then join them all like
std::vector<std::thread> threads;
threads.reserve(inputs.size());
for (int unsigned i = 0; i < inputs.size(); i++) {
threads.push_back(std::thread{thread_function, inputs.at(i)};
}
// now all threads are running, or waiting to run
for (int unsigned i = 0; i < inputs.size(); i++) {
threads[i].join();
}
// now all threads have been joined
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.