要了解C ++中的线程,我做了这个睡眠排序实现。大多数情况下,它可以正常工作。但是,也许每十五分钟运行一次,我的睡眠排序函数返回的向量将包含一些垃圾值。有人知道是什么原因造成的吗?
这是我的输出的屏幕截图:
这是我的代码:
#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;
}
答案 0 :(得分:5)
没有什么可以阻止两个线程同时或重叠地调用push_back
。您需要互斥锁或其他某种形式的同步。