我正在用C ++写一个quicksort并且它工作正常,但是当我尝试使用多个线程(使用C ++ 11线程)时,它会随机崩溃。有时它会说“没有活动异常时调用终止”或“调用纯虚方法”,或者只是简单地崩溃而没有任何错误消息。我使用的线程越多,它就越频繁崩溃。
有人能告诉我我做错了什么吗? 我正在使用minGW x64-4.8.1-release-posix-seh-rev5和-Ofast优化标志。
template<class T>
T partition(T begin, T end, T pivot){
T result_pivot;
std::swap(*pivot, *(end - 1)); /* puts pivot to the end */
pivot = end - 1;
T it_right = end - 1;
/* starts searching an item from the left that is bigger than the pivot */
for(T it_left = begin; it_left < it_right; ++it_left){
if(*pivot <= *it_left){
while(*(--it_right) > *pivot && it_right != it_left)
/* empty - searches for an item that is smallar than the pivot from the right */ ;
if(it_right != it_left){ /* if such an item is found and the pointers do not meet we swap them */
std::swap(*it_right, *it_left);
}
else break; /* if the pointers do meet, stop */
}
}
/* puts the pivot back and returns the pivot */
std::swap(*pivot, *it_right);
return it_right;
}
struct running_threads {
int max_threads = 8;//std::thread::hardware_concurrency();
std::mutex mutex;
int num_of_threads = 1;
void operator++(){
mutex.lock();
++num_of_threads;
mutex.unlock();
}
void operator--(){
mutex.lock();
--num_of_threads;
mutex.unlock();
}
} thr;
template<class T>
void swap_quick_sort(T begin, T end){
size_t size = end - begin;
/* stopping criteria */
if(size <= 3){
if(size == 3)
order3(begin[0], begin[1], begin[2]);
else if(size == 2 && begin[0] > begin[1])
std::swap(begin[0], begin[1]);
return;
}
/* the pivot is the median of the first, middle and last item */
T pivot = median(begin, begin + size/2, begin + size - 1);
T result_pivot = partition(begin, end, pivot);
/* since creating/joining threads is slow,
we only create a new thread when the array is big enough */
if(size > 30000 && thr.num_of_threads < thr.max_threads){
std::thread A(swap_quick_sort<T>, begin, result_pivot);
++thr;
swap_quick_sort(result_pivot + 1, end);
A.join();
--thr;
}
else {
swap_quick_sort(begin, result_pivot);
swap_quick_sort(result_pivot + 1, end);
}
}
template<class T>
void order3(T& a, T& b, T& c){
if (a <= b && a <= c){
if (b > c)
std::swap(c, b);
}
else if(b <= a && b <= c)
if (a <= c)
std::swap(a, b);
else {
std::swap(a, b);
std::swap(b, c);
}
else
if (a <= b){
std::swap(a, c);
std::swap(b, c);
}
else
std::swap(a, c);
}
template<class T>
T median(T a, T b, T c){
if (*a <= *b && *a <= *c){
if (*b <= *c)
return b;
else
return c;
}
else if(*b <= *a && *b <= *c){
if (*a <= *c)
return a;
else
return c;
}
else if(*a <= *b)
return a;
else
return b;
}
在main函数中,我用随机元素向量调用它。