c++ - 如何实现线程同步对 vector 的 vector 进行排序?

标签 c++ multithreading asynchronous threadpool synchronous

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

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


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;
}

当同步排序必须更快时,两种方法花费的时间相同。

最佳答案

您需要保留线程并在循环后加入它们。

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++ - 如何实现线程同步对 vector 的 vector 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54297945/

相关文章:

python - 如何在 Raspberry Pi 上使用 TBB 构建 OpenCV?

c# - 如何使用 Dispatcher 设置 Image.Source 属性?

node.js - Node.js 什么时候阻塞?

java - Java内存模型如何确保所有线程看到的变量值一致?

c++ - 在 Qt GUI 事件线程中检测到 "I' m 正在运行

c# - 如何捕获 lambda 表达式中外部变量的值?

c# - 我怎样才能等待一系列任务并停止等待第一个异常?

c++ - 使用 constexpr 编译时间哈希

C++ 如果输入 vector 与输出 vector 相同,如何修复不清除输入 vector 的错误?

c++ - 从析构函数访问模板类构造函数的参数,可以吗?