-4 c++ sorting multithreading c++11
要了解C++中的线程,我做了这个睡眠排序实现.大多数时候,它工作正常.但是,也许每15个左右运行一次,我的睡眠排序函数返回的向量将包含一些垃圾值.有谁知道是什么原因引起的?
这是我输出的屏幕截图:

这是我的代码:
#include <stdio.h>
#include <thread>
#include <chrono>
#include <vector>
std::vector<unsigned int> sleepSort(std::vector<unsigned int> toSort){
//vector to hold created threads
std::vector<std::thread> threadList;
//vector to hold sorted integers
std::vector<unsigned int> sorted;
//create a thread for each integer, n, in "toSort" vector
//each thread sleeps for n seconds then adds n to "sorted" vector
for(int i = 0; i < toSort.size(); i++){
threadList.push_back(
std::thread(
[](int duration, std::vector<unsigned int>& v){
std::this_thread::sleep_for((std::chrono::seconds)duration);
v.push_back(duration);
}, toSort.at(i), std::ref(sorted)
)
);
}
//wait for each thread to finish before returning sorted
for(auto& thread : threadList){
thread.join();
}
return sorted;
}
int main(int argc, char **argv)
{
std::vector<unsigned int> v {5, 14, 6, 12, 17, 3, 15, 4, 10, 1,
2, 5, 7, 8, 9, 13, 11, 11, 11, 16
};
printf("Unsorted:\n");
for(int i = 0; i < v.size(); i++)
printf("%d\n", v.at(i));
printf("Sorting...\n");
v = sleepSort(v);
printf("Sorted:\n");
for(int i = 0; i < v.size(); i++)
printf("%d\n", v.at(i));
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |