[英]Quick sort with multithreading in c++
我使用multi-thread
方法實現了一個quicksort
程序,在C ++中使用Portfolio任務。
組合任務的方法是維護任務隊列。 每個免費線程從投資組合中挑選一個任務,執行它,如果需要,生成新的子任務並將它們放入投資組合中
但我不確定什么是對的! 在我看來,在一個thread
,算法的工作速度比兩個或四個thread
快。 我能以某種方式搞砸同步嗎?
謝謝任何人幫助我。
碼:
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <queue>
#include <vector>
#include <set>
#include <ctime>
#include <algorithm>
using namespace std;
//print array
template <typename T>
void print(const vector<T> &arr)
{
for (size_t i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
cout << endl;
}
//queue tasks
queue< pair<int, int> > tasks;
//mutexs for set and queue task
mutex q_mutex, s_mutex;
//condition variable
condition_variable cv;
//set
set<int> ss;
//partition algorithm
template <typename T>
int partition(vector<T> &arr, int l, int r)
{
T tmp = arr[r]; //as pivot element
int i = l - 1;
for (int j = l; j <= r - 1; j++)
if (arr[j] < tmp)
{
i++;
swap(arr[i], arr[j]);
}
swap(arr[i + 1], arr[r]);
i++;
return i;
}
//quick sort
template <typename T>
void quick_sort(vector<T> &arr)
{
while (true)
{
unique_lock<mutex> u_lock(q_mutex); //lock mutex
//sort is fineshed
if ( ss.size() == arr.size() ) //u_lock.unlock()
return;
//if queue task is not empty
if ( tasks.size() > 0 )
{
//get task from queue
pair<int, int> cur_task = tasks.front();
tasks.pop();
int l = cur_task.first, r = cur_task.second;
if (l < r)
{
int q = partition(arr, l, r); //split array
//Add indexes in set
s_mutex.lock();
ss.insert(q);
ss.insert(l);
ss.insert(r);
s_mutex.unlock();
//push new tasks for left and right part
tasks.push( make_pair(l, q - 1) );
tasks.push( make_pair(q + 1, r) );
//wakeup some thread which waiting
cv.notify_one();
}
}
else
//if queue is empty
cv.wait(u_lock);
}
}
//Size array
const int ARR_SIZE = 100000;
//Count threads
const int THREAD_COUNT = 8;
thread thrs[THREAD_COUNT];
//generatin array
void generate_arr(vector<int> &arr)
{
srand(time( NULL ));
std::generate(arr.begin(), arr.end(), [](){return rand() % 10000; });
}
//check for sorting
bool is_sorted(const vector<int> &arr)
{
for (size_t i = 0; i < arr.size() - 1; i++)
if ( ! (arr[i] <= arr[i + 1]) )
return false;
return true;
}
int main()
{
//time
clock_t start, finish;
vector<int> arr(ARR_SIZE);
//generate array
generate_arr(arr);
cout << endl << "Generating finished!" << endl << endl;
cout << "Array before sorting" << endl << endl;
//Before sorting
print(arr);
cout << endl << endl;
cout << "Checking is_sorted finished! The result is " << (is_sorted(arr) == 0? "false": "true") << "." << endl << endl;
//add task
tasks.push( make_pair(0, arr.size() - 1) );
//==================================================
start = clock();
for (int i = 0; i < THREAD_COUNT; i++)
thrs[i] = thread( quick_sort<int>, ref(arr) );
finish = clock();
//==================================================
for (auto& th : thrs)
th.join();
cout << "Sorting finished!" << endl << endl;
cout << "Array after sorting" << endl << endl;
//After sorting
print(arr);
cout << endl << endl;
cout << "Checking is_sorted finished! The result is " << (is_sorted(arr) == 0? "false": "true") << "." << endl << endl;
cout << "Runtime: " << (double)(finish - start) / CLOCKS_PER_SEC << endl;
return 0;
}
與性能問題相關的線程數要多得多。 其中,
您需要具有實際的並發性,而不僅僅是多個線程。 正如@ Rakete1111和@ user1034749都觀察到的那樣,你沒有。
標准快速排序具有良好的引用局部性,特別是當分區大小變小時,但是由於給定數組元素的責任很可能在每次分區時交換到不同的線程,因此您的技術會拋棄很多。
此外,互斥操作並不是特別便宜,而且當分區變小時,相對於實際排序的數量,你會開始做很多相關操作。
使用比物理內核更多的線程是沒有意義的。 四個線程可能不是太多,但它取決於您的硬件。
以下是一些可以提高多線程性能的方法:
在方法quick_sort()
,不要在實際排序期間鎖定互斥鎖q_mutex
,就像你當前所做的那樣(你使用的unique_lock
構造函數鎖定互斥鎖,並且你不會在unique_lock
的生命周期內解鎖它)。
切換到小於某個閾值大小的分區的普通遞歸技術。 你必須進行測試才能找到一個好的特定閾值; 也許它需要是可調的。
在每個分區中,讓每個線程只將一個子分區發布到組合中; 讓它以遞歸的方式處理另一個 - 或者更好,迭代地處理。 事實上,將它作為您發布的較小的子分區,因為這將更好地限制投資組合的大小。
您還可以考慮增加運行測試的元素數量。 100000並不是那么多,您可能會看到更大問題的不同性能特征。 在現代硬件上進行這樣的測試,1000000個元素根本不合理。
在我看來,你應該將投資組合任務的行為捕捉到一個類中。
template <typename TASK, unsigned CONCURRENCY>
class Portfolio {
std::array<std::thread, CONCURRENCY> workers_;
std::deque<TASK> tasks_;
std::mutex m_;
std::condition_variable cv_;
std::atomic<bool> quit_;
void work () {
while (!quit_) {
TASK t = get();
if (quit_) break;
t();
}
}
TASK get () {
std::unique_lock<std::mutex> lock(m_);
while (tasks_.empty()) {
cv_.wait(lock);
if (quit_) return TASK();
}
TASK t = tasks_.front();
tasks_.pop_front();
if (!tasks_.empty()) cv_.notify_one();
return t;
}
public:
void put (TASK t) {
std::unique_lock<std::mutex> lock(m_);
tasks_.push_back(t);
cv_.notify_one();
}
Portfolio ();
~Portfolio ();
};
構造函數將使用每個調用work()
方法的線程初始化worker。 析構函數將設置quit_
,發出所有線程的信號,並加入它們。
然后,您的快速排序可以簡化:
template <typename T, unsigned WORK_SIZE, typename PORTFOLIO>
QuickSortTask {
std::reference_wrapper<PORTFOLIO> portfolio_;
std::reference_wrapper<std::vector<T>> arr_;
int start_;
int end_;
QuickSortTask (PORTFOLIO &p, std::vector<T> &a, int s, int e)
: portfolio_(p), arr_(a), start_(s), end_(e)
{}
void operator () () {
if ((end_ - start_) > WORK_SIZE) {
int p = partition(arr_, start_, end_);
portfolio_.put(QuickSortTask(portfolio_, arr_, start_, p-1));
portfolio_.put(QuickSortTask(portfolio_, arr_, p+1, end_));
} else {
regular_quick_sort(arr_, start_, end_);
}
}
};
不幸的是,這種制定並行快速排序的方法不太可能產生大的加速。 您要做的是並行化分區任務,這需要至少一個單線程計算通過(涉及數據比較和交換),然后才能開始並行化。
首先將數組划分為WORK_SIZE
子數組,並行地對每個數組執行快速排序,然后合並結果以創建排序向量可能會更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.