如何实现线程同步对向量的向量进行排序?

How to implement threads to sort a vector of vectors synchronously?

我正在创建一个包含整数向量的向量,我的想法是通过为每个整数调用带线程的冒泡排序来对每个整数向量进行排序,然后打印执行时间。

我试图在每次迭代中实现一个线程,但不起作用


vector<int> bubbleSort(vector<int>);

void asynchronousSort(vector<vector<int>> pool){
    double executionTime;

    clock_t tStart = clock();
    for(int i = 0; i < pool.size(); i++){
        thread t (bubbleSort, pool[i]);
        t.join();
    }

    executionTime = (double)(clock() - tStart)/CLOCKS_PER_SEC;
    cout << "Time :" << executionTime<< "s." << endl ;
}

void synchronousSort(vector<vector<int>> pool){
    double executionTime;
    clock_t tStart = clock();

    for(int i = 0; i < pool.size(); i++){
        pool[i] = bubbleSort(pool[i]);
    }

    executionTime = (double)(clock() - tStart)/CLOCKS_PER_SEC;
    cout << "Time :" << executionTime<< "s." << endl ;
}

int main(int argc, const char * argv[]) {

    int selectMethod;
    vector<vector<int>> pool(10);
    //Create 10 lists with 10000 numbers in decrement.
    for (int i = 0; i < 10; i++) {
        vector<int> temp;
        for(int j = 10000; j > 0; j--){
            temp.push_back(j);
        }
        pool.push_back(temp);
    }

    cout << "Select method 1)Asynchronously. 2)Synchronously. (1/2): ";
    cin >> selectMethod;

    if(selectMethod == 1){
        asynchronousSort(pool);
    }else{
        synchronousSort(pool);
    }
    return 0;
}

两种方法所用时间相同,同步排序必须更快。

在您的 for 循环中,您等待一个线程完成 (t.join()),因此没有同步排序。

for(int i = 0; i < pool.size(); i++){
        thread t (bubbleSort, pool[i]);
        t.join();
    }

改用detach(),然后在函数returns之前等待所有线程(例如,将线程*存储在向量中,然后将所有线程加入for循环)。

也就是说,创建线程需要时间,因此对于快速操作而言,它可能没有您想象的那么快。如果这是 Windows,你可以使用我的 Threadpool API class, documented here.

您需要在循环后保留 threadjoin 它们。

void asynchronousSort(vector<vector<int>> pool){
    double executionTime;
    vector<thread> threads;

    clock_t tStart = clock();
    for(int i = 0; i < pool.size(); i++){
        threads.emplace_back(bubbleSort, pool[i]); // make threads directly inside the vector
                                                   // saves having to std::move them
    }
    for(thread & t:threads) // now that all the threads are up (and maybe running), join them
    {
        t.join();
    }
    // now we can get the execution time
    // note: unless pool is large you may miss it. 
    executionTime = (double)(clock() - tStart)/CLOCKS_PER_SEC;
    cout << "Time :" << executionTime<< "s." << endl ;
}

请注意,这并不是真正的线程池。线程池是您保留并分配作业的线程池。这只是一堆thread。另请注意,如果线程池需要穿着红色和黑色并与观众交谈,那么您就有真正的问题了。立即寻求帮助。

如果您有支持执行策略的 C++17 编译器(如 VS2017),使用 std::for_each(std::execution::par, ... 可能是一个选项。

#include <algorithm>
#include <execution>

void asynchronousSort(vector<vector<int>>& pool) {
    std::for_each(std::execution::par, pool.begin(), pool.end(), [](auto& v) {
        // used std::sort instead
        std::sort(v.begin(), v.end());
    });
}