Reputation: 41
I have some issues with C++ thread library. I have adapted my old code for optimization of a new problem and suddenly an uncaught exception is thrown (During runtime). Some threads are joined successfully, but there's always at least one throwing an exception. Only thing which I changed in the code, was data representation. They were earlier held in 2D arrays and now I am using 1D vectors. Here is the exact runtime error I receive:
libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: thread::join failed: Invalid argument
Below I provide the minimal reproducible example, throwing the exact same exception like in the case of the complete code.
Here is the main function:
#include <iostream>
#include <thread>
#include <vector>
void reforming(const int, const std::vector<int>&, const std::vector<double>&, const std::vector<double>&);
int main() {
int i, k;
int spec_max = 10;
int seg_max = 4;
size_t pop_size = spec_max * seg_max;
std::vector<int> seg(pop_size);
std::vector<double> por(pop_size);
std::vector<double> por_s(pop_size);
for(i = 0; i < pop_size; i++){
if(i % 2 == 0){
seg[i] = 1;
por[i] = 0.5;
por_s[i] = 0.0015;
} else {
seg[i] = 0;
por[i] = 0.7;
por_s[i] = 0.002;
}
}
std::vector<std::thread> Ref(spec_max);
for(k = 0; k < spec_max; k++){
Ref.emplace_back(reforming, k, seg, por, por_s);
}
for(auto &X : Ref){
X.join();
}
return 0;
}
and the "reforming" function:
#include <iostream>
#include <vector>
void reforming(const int m, const std::vector<int>& cat_check, const std::vector<double>& por,
const std::vector<double>& por_s){
std::cout << m << " Hello from the thread\n";
}
I am using the CLion software on MacOS Catalina and currently have no other OS available to test the code.
Upvotes: 1
Views: 298
Reputation: 136515
The following code:
std::vector<std::thread> Ref(spec_max);
for(k = 0; k < spec_max; k++){
Ref.emplace_back(reforming, k, seg, por, por_s);
}
creates 2 * spec_max
threads, the first spec_max
threads are default-initialized. Trying to join a default-initialized thread throws std::system_error
.
A fix:
std::vector<std::thread> Ref;
Ref.reserve(spec_max);
for(k = 0; k < spec_max; k++){
Ref.emplace_back(reforming, k, seg, por, por_s);
}
Upvotes: 4