// First.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <random>
#include <thread>
#include <mutex>
#include <memory>
using namespace std;
/** @ return the position of x */
int partition(int arr[], int beg, int end){ /** 0,1,2,3,...,end*/
int ramdom_index = rand() % (end - beg + 1) + beg;
swap(arr[beg], arr[end]);
int x = arr[beg];
size_t i = beg + 1;
for (size_t j = beg + 1; j <= end; j++){
if (arr[j] < x)
swap(arr[i++], arr[j]);
}
swap(arr[beg], arr[--i]);
return i;
}
//void quickSort(int arr[], int beg, int end){
// if (beg < end){
// int mid = partition(arr, beg, end);
// quickSort(arr, beg, mid - 1);
// quickSort(arr, mid + 1, end);
//
// }
// /** return if(beg >= end) */
//}
size_t size = 10000000;
const int minSizeOfPerThread = 100000;
static int threadNum = 0;
mutex mu;
void quickSort(int arr[], int beg, int end){
if (beg < end){
int mid = partition(arr, beg, end);
if (mid - beg > minSizeOfPerThread){
thread thr1(quickSort, ref(arr), beg, mid - 1);
thread thr2(quickSort, ref(arr), mid + 1, end);
thr1.join();
thr2.join();
lock_guard<mutex>muguard(mu);
threadNum += 2;
}
else
{
quickSort(ref(arr), beg, mid - 1);
quickSort(ref(arr), mid + 1, end);
}
}
/** return if(beg >= end) */
}
void test(){
unique_ptr<int[]>testArr0(new int[size]);
for (size_t i = 0; i < size; ++i)
testArr0[i] = rand();
time_t timeStart = clock();
quickSort(testArr0.get(), 0, size - 1);
time_t timeEnd = clock();
cout << "sort time is " << (timeEnd - timeStart) << endl;
/*for (size_t i = 0; i < size; ++i)
cout << testArr0[i] << " ";
*/cout << "test over\n" << endl;
cout << "threadNum Is " << threadNum << endl;
}
void test2(){
unique_ptr<int[]>testArr0(new int[size]);
for (size_t i = 0; i < size; ++i)
testArr0[i] = rand();
time_t timeStart = clock();
sort(testArr0.get(), testArr0.get() + size - 1);
time_t timeEnd = clock();
cout << "sort time is " << (timeEnd - timeStart) << endl;
/*for (size_t i = 0; i < size; ++i)
cout << testArr0[i] << " ";
*/cout << "test over\n" << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
test();
test2();
system("pause");
return 0;
}
c++11 版多线程 快速排序
最新推荐文章于 2022-09-11 22:26:45 发布