0

Just started learning multithreading in c++ and wanted to experiment with it. So i'm trying to split an array into the number of physical cores (nt-variable) , sort each part on an independed thread and then merge them , but i get the error terminate call without an active exception.

void MergeSortV5(int *v,int ii,int is,int nt)
{

    int lp=is/nt;
    thread t[nt-1];
    int ai,as=0;
    for(int i=0; i<nt-1; i++)
    {
        ai=as+1;
        as=ai+lp-1;
        t[i]=thread (MergeSortV2,v,ai,as);
    }
    ai=as+1;
    as=is;
    t[nt-1]=thread (MergeSortV2,v,ai,as);
    for(int i=0; i<nt; i++)
            t[i].join();
}

MergeSortV2 is a regular merge sort. From what i understand this exception is caused because the threads finish faster than the main program (which surely was the case in the small array examples i tried), but i can't seem to fix it , i tried detaching the threads and joining them later if possbile , or imediatly joing them but the error still occurs.

Paul
  • 776
  • 1
  • 5
  • 18

1 Answers1

2

The t array is allocated with the wrong size (nt rather than nt-1). Moreover, please consider a using dynamically allocated array since nt is not defined at compile time (see here for more information).

thread* t = new thread[nt];
[...]
delete[] t;

Or event better: a std::vector<std::thread> !

Jérôme Richard
  • 41,678
  • 6
  • 29
  • 59