std::thread
thread類表示各個線程的執行。
在多線程環境下,一個線程和其餘線程同時執行指令序列,並共享地址空間。
一個被初始化的線程對象表明一個正在執行的線程。好比一個線程對象是可鏈接的,它有一個惟一的線程ID。
一個默認的沒有初始化的線程對象不是可連接的,它的線程ID時和其餘沒有可鏈接的線程公用的。
一個可連接的線程變爲不可連接的線程或者當對它調用join或者detach。
Member types
-
id
-
Thread id
(public member type )
-
native_handle_type
-
Native handle type
(public member type )
Member functions
-
(constructor)
-
Construct thread
(public member function )
-
(destructor)
-
Thread destructor
(public member function )
-
operator=
-
Move-assign thread
(public member function )
-
get_id
-
Get thread id
(public member function )
-
joinable
-
Check if joinable
(public member function )
-
join
-
Join thread
(public member function )
-
detach
-
Detach thread
(public member function )
-
swap
-
Swap threads
(public member function )
-
native_handle
-
Get native handle
(public member function )
-
hardware_concurrency [static]
-
Detect hardware concurrency
(public static member function )
Non-member overloads
-
swap (thread)
-
Swap threads
(function )
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
// thread example
#include <iostream> // std::cout
#include <thread> // std::thread
void foo()
{
// do stuff...
}
void bar(int x)
{
// do stuff...
}
int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar,0); // spawn new thread that calls bar(0)
std::cout << "main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
std::cout << "foo and bar completed.\n";
return 0;
} |
|
Output:
main, foo and bar now execute concurrently...
foo and bar completed.
|