gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:43:28 25 4
gpt4 key购买 nike

我正在创建一个包含整数 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com