編譯器: g++ 4.5
編譯選項: -std=c++0x
鏈接選項: –pthread
完整編譯鏈接命令: g++ –O2 –o example example.cc -std=c++0x -pthread
頭文件:
條目 頭文件 thread <thread> Mutual exclusion <mutex> Condition variables <condition_variable> Futures <future>如果想在一個線程中執行一個函數 f ,那麼這個線程可以這樣創建:
? 1std::thread t( f );
如果函數有參數,那麼直接把參數列在後邊即可:
? 1 2 3 4 5void hello_from( const char* str const )
{
std::cout << "hello from " << str << "
";
}
std::thread t( hello_from, "thread t" );
多個參數的函數也是如此:
? 1 2 3 4 5void max( const long m, const long n )
{
std::cout << "max(" << m << ", " << n << ")=" << (m>n?m:n) << "
";
}
std::thread t( max, 13, 31 );
可以依此類推到3個、4個……參數的函數情形。
只要不把 main 函數也弄進去,編譯器統統接受:
? 1 2 3 4void try_start_program_here()
{
std::thread t( main ); //error
}
把仿函數依樣搬進去:
? 1 2 3 4 5 6 7struct say_hello