C++版のSleep sort

元ネタはここ→http://dis.4chan.org/read/prog/1295544154
ちなみにここで知った→常識を覆すソートアルゴリズム!その名も"sleep sort"! - Islands in the byte stream
考えた人天才だろ。
※5/21密かに修正(scoped_lock使おうね!)

#include <iostream>

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind/bind.hpp>


#define BOOST_SLEEP(n) boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds((n)))

boost::mutex m;

void func(int n)
{
    BOOST_SLEEP(n * 100);

    {
        boost::mutex::scoped_lock lock(m);
        std::cout << n << " ";
    }
    // m.lock();
    // std::cout << n << " ";
    // m.unlock();
}

int main()
{
    int a[] = {3, 1, 8, 7, 2, 4, 9, 6, 0, 5};
    int n = sizeof(a) / sizeof(a[0]);

    boost::thread_group group;

    for (int i = 0; i < n; ++i)
        group.create_thread(boost::bind(func, a[i]));

    group.join_all();

    return 0;
}

実行結果*1

0 1 2 3 4 5 6 7 8 9 



ついでにC++0xでソート部分を関数にしてみた

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind/bind.hpp>


#define BOOST_SLEEP(n) boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds((n)))

std::vector<int> SleepSort(std::vector<int> v)
{
    boost::mutex m;
    std::vector<int> ret;

    std::function<void(int)> f = [&](int n) {
        BOOST_SLEEP(n * 100);

        {
            boost::mutex::scoped_lock lock(m);
            ret.push_back(n);
        }
        // m.lock();
        // ret.push_back(n);
        // m.unlock();
    };


    boost::thread_group group;

    std::for_each(v.begin(), v.end(), [&](int n) {
        group.create_thread(boost::bind(f, n));
    });

    group.join_all();

    return ret;
}

int main()
{
    int a[] = {3, 1, 8, 7, 2, 4, 9, 6, 0, 5};
    int n = sizeof(a) / sizeof(a[0]);
    std::vector<int> v(a, a + n);

    v = SleepSort(std::move(v));

    std::for_each(v.begin(), v.end(), [](int n) {
        std::cout << n << " ";
    });

    return 0;
}

実行結果*2

0 1 2 3 4 5 6 7 8 9 

*1:表示された時笑った

*2:当然同じ