c++11中的睡眠排序

sleep sort in c++ 11

本文关键字:排序 c++11      更新时间:2023-10-16

伙计们,我正在考虑一种排序方法,它被称为睡眠排序

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int c, char **v)
{
    while (--c > 1 && !fork());
    sleep(c = atoi(v[c]));
    printf("%dn", c);
    wait(0);
    return 0;
}

我不明白一件事,在c++11中fork等价物是什么?我指的是新版本的c++?我可以写这样的等待函数

void wait ( int seconds ){
    clock_t endwait;
    endwait = clock () + seconds * CLOCKS_PER_SEC ;
    while (clock() < endwait) {}
}

但是fork()呢?我试着用代码

#include<iostream>
#include<time.h>
using namespace std;;
void wait ( int seconds ){
    clock_t endwait;
    endwait = clock () + seconds * CLOCKS_PER_SEC ;
    while (clock() < endwait) {}
}
void Sort(int c,int a[])
{
    while(--c>1)
    {
        wait(c=a[c]);
        cout<<c<<"  ";
    }
 }
int main()
{
    int a[]={1, 3, 2, 11, 6, 4};
    int c=5;
    Sort(c,a);
    wait(0);
    return 0;
}

但它没有给我排序输出,它的输出像6 4 1,并完成了,所以请告诉我如何纠正它?

不能像在wait()函数中那样简单地延迟;这是通过为每个参数创建一个新的进程(通过fork())并让每个参数并行休眠来实现的;你的提议会让每个元素串联睡眠,这样就不会给人一种错觉。

至于what is fork equivalent in c++ 11?——fork()不是C或C++所特有的;这是操作系统提供的功能。

您还没有理解要点。等待必须并行运行(由fork触发,它为每个项目创建一个新线程)。

虽然还有更多的事情要谈,但我只回答你的主要问题。

您已经设置了c=5,尽管您有6个数字,并且您有while(--c>1),因此,如果您计算,它只运行循环3次,因为如果您在运算符之前添加--,它将首先减去1,然后进行比较。

  • c=5
  • while(--c>1)[减去5的1=4并检查是否大于1]//运行它
  • while(--c>1)[减去4的1=3并检查是否大于1]//运行它
  • while(--c>1)[减去3的1=2并检查是否大于1]//运行它
  • while(--c>1)[减去2的1=1并检查是否大于1]//不运行

您必须将c更改为您拥有的数字数量:c=6,然后更改while循环,如下所示:while(c-->0)

下面是一个使用Win32:的C++实现

#include <windows.h>
#include <iostream>
using namespace std;
DWORD threadFunc(LPVOID param)
{
    long val = (long)param;
    Sleep((int)val * 1000);
    cout << val << " ";
    return 0;
}
int main()
{
    HANDLE handles[6];
    int arr[] = {1, 3, 2, 11, 6, 4};
    for(int i = 0; i < 6; i++)
    {
        handles[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&threadFunc, 
                                  (LPVOID)arr[i], 0, NULL);
    }
    WaitForMultipleObjects(6, handles, 1, INFINITE);
}

跨平台版本。支持负数!

#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
#include <algorithm>
template< typename It >
void sleepSort( const It& begin, const It& end )
{
    if ( begin == end )
        return;
    const auto [min, max] = std::minmax_element( begin, end );
    for ( auto it = begin; it != end; ++it )
    {
        std::thread( [min = *min, i = *it]
            {
                std::this_thread::sleep_for( std::chrono::milliseconds( i - min ) );
                std::cout << i << std::endl;
            } ).detach();
    }
    std::this_thread::sleep_for( std::chrono::milliseconds( *max - *min + 1 ) );
}
int main( int argc, char *argv[] )
{
    std::vector<int> v = { 20, 5, 15, 10, -5, };
    sleepSort( v.begin(), v.end() );
    return 0;
}

输出:

-5 5 10 15 20