c++11 版多线程 快速排序
2014-08-18 16:36
218 查看
// 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多线程 生产者-消费者模型/条件变量condition_variable
- C++11 多线程 基础
- c++11 多线程实现生产者消费者模型
- C++11并发编程1——C++11多线程简介
- C++11 并发指南九(综合运用: C++11 多线程下生产者消费者模型详解)
- c++11 多线程间共享数据 <c++ concurrency in action>
- c++11 跨平台多线程demo和qt 静态链接
- C++11 多线程:数据保护
- C++11多线程(十一):《atomic类型详解二:std::atomic》
- C++11 多线程
- C++11多线程互斥锁的使用
- C++11多线程生产者与消费者
- C++11 多线程
- C++11:并发、多线程
- 简单的基于libcurl和c++11 thread多线程的多线程下载程序
- C++11多线程中std::call_once的使用
- C++11多线程
- C++11之多线程初探
- C++11多线程
- C++11 并发与多线程(一)