I'm learning parallel programming and there is an example in my lecture for it. We have an array for storing 20 fibonacci numbers and basically, for computing each of them, a thread is created. This is the code for the fibonacci function:
unsigned int fibonacci(unsigned int n) {
if(n==0)
return 0;
unsigned int f0 = 0, f1 = 1, f2;
for (auto i=1u; i < n; i++) {
f2 = f0 + f1;
f0 = f1;
f1 = f2;
}
return f1;
}
This is the code for the main method:
int main(int argc, char **argv) {
std::vector<std::thread> threads;
unsigned int results[20];
for(auto i=0u; i < 20; i++) {
auto f = rand() % 30;
threads.push_back(std::thread([&](){
results[i] = fibonacci(f);
}));
}
std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
for(auto& r: results) {
std::cout << r << " ";
}
std::cout << std::endl;
return 0;
}
The numbers are calculated, but the program terminates with status -1073741819 (0xC0000005). I followed this post, but even with applying emplace.back()
there is no change. So what might be the reason for this error?