Friday, June 17, 2011

SleepSort implementation with c++0x std::thread

Here it is the Sleep Sort

#include <thread>
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

void sleep_sort(int n)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(n));
    std::cout << n << " ";
}

int main()
{
    std::vector<int> a = {1500, 200, 100, 300, 400, 300};

    std::vector<std::thread> threads;
    for(std::vector<int>::iterator it = a.begin(); it != a.end(); it++)
    {
        threads.push_back(std::thread(sleep_sort, *it));
    }

    std::for_each(threads.begin(), threads.end(),
        std::mem_fn(&std::thread::join));

    std::cout << std::endl;

    return 0;
}