C++0x で sleep sort 書いてみた (was そういえば C++0x での sleep sort ってこんな感じでいいのかな)
GCC 4.6.0 をがんばって OSX に入れたのに std::thread 使えなくて泣きながら修正。こんな感じすね。
#include <cstdio> #include <vector> extern "C" { #include <pthread.h> #include <unistd.h> } int main(int, char**) { int values[] = { 1, 9, 3, 6 }; std::vector<pthread_t> threads; for (auto& v : values) { pthread_t tid; pthread_create(&tid, NULL, [](void* _v) -> void* { int v = *reinterpret_cast<int*>(_v); sleep(v); printf("%d\n", v); return NULL; }, &v); threads.push_back(tid); } for (auto tid : threads) pthread_join(tid, NULL); return 0; }
std::thread が使えればこうなる。
int main(int, char**) { int values[] = { 1, 9, 3, 6 }; std::vector<std::thread> threads; for (auto v : values) threads.emplace_back([v]() { sleep(v); printf("%d\n", v); }); for (auto& thread : threads) thread.join(); return 0; }
コンパイラないので試せないわ。