是什么导致了此睡眠排序实现中的未定义行为? < >学习C++中的线程,我做了这个睡眠排序实现。大多数情况下,它工作正常。然而,大约每运行15次,就有一次,我的sleep sort函数返回的向量将包含一些垃圾值。有人知道这是什么原因吗

是什么导致了此睡眠排序实现中的未定义行为? < >学习C++中的线程,我做了这个睡眠排序实现。大多数情况下,它工作正常。然而,大约每运行15次,就有一次,我的sleep sort函数返回的向量将包含一些垃圾值。有人知道这是什么原因吗,c++,multithreading,sorting,c++11,C++,Multithreading,Sorting,C++11,以下是我的输出的屏幕截图: 这是我的密码: #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::

以下是我的输出的屏幕截图:

这是我的密码:

#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;
}
#包括
#包括
#包括
#包括
std::vector sleepSort(std::vector toSort){
//用于保存已创建线程的向量
std::向量线程列表;
//用于保存排序整数的向量
std::向量排序;
//为“toSort”向量中的每个整数n创建一个线程
//每个线程休眠n秒,然后将n添加到“排序”向量
对于(int i=0;i
没有任何东西可以阻止两个线程同时调用
后推
。你需要一个互斥体或其他形式的同步。< /P>我只是好奇,为什么你在C++程序中使用<代码> PrimTf<代码>?您似乎也知道rangefor循环,并在一个地方使用它,但在另一个地方却没有。为什么?哦,而且永远不要在C++中使用C风格的铸件!如果你这样做,那通常是你做错事的标志,并且学习如何正确使用它。@一些程序员在C++中使用PRTFF是坏的做法吗?还有什么其他方法可以在C++中进行转换?我只看到它是C风格的。你的编译器和编译器版本是什么?,