【发布时间】:2019-06-15 07:32:07
【问题描述】:
我正在创建一个包含整数向量的向量,其想法是通过调用带有线程的冒泡排序来对每个整数向量进行排序,然后打印执行时间。
我试图在每次迭代中实现一个线程但不起作用
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;
}
这两种方法所用的时间相同,而 sinchronousSort 必须更快。
【问题讨论】:
-
Related: 除非你对一些很小的东西进行排序(我所说的很小,我的意思是可能有十几个槽),否则“必须更快”和“冒泡排序”这两个词永远不会在同一个算法中重合,除非“从不使用”一词在后者之前。也就是说,您的函数名称是反对的。异步应该是线程的,同步应该是直接调用的。你应该站起来一个线程向量,每个线程都得到一个要排序的向量,然后在它们都站起来后将它们 all 加入。或者更好的是,使用池和输入队列。
标签: c++ multithreading asynchronous threadpool synchronous