[Solved] C++ Threading Error


The issue: you are calling join method for empty thread – you cannot do this, when you call join on non-joinable thread you will get exception.

In this line

thread threads[MAX_THREADS];

you created MAX_THREADS threads using its default constructor. Each thread object after calling default ctor is in non-joinable state. Before calling join you should invoke joinable method, if it returns true you can call join method.

        for (int i = 0; i < MAX_THREADS; i++){
           if(threads[i].joinable())
              threads[i].join();
        }

Now your code crashes when i = 0 because you increment currentThread at the beginning of your for loop:

for (int slice = 0; slice < convertToVoxels(ARM_LENGTH); slice+=MAX_SLICES_PER_THREAD){
  currentThread++; // <---

and you leave threads[0] with empty object while doing this assignment (before first assignment currentThread is 1)

    threads[currentThread] = thread(buildDensityModel, slice * MAX_SLICES_PER_THREAD, currentSlice);

2

solved C++ Threading Error