在C++ 11之前,官方並沒有支持線程庫。C++ 11通過標准庫引入了對 thread 類的支持,大大方便了完成多線程開發的工作。
std::thread 構造函數
(1)thread() noexcept;
(2)thread( thread&& other ) noexcept;
(3)template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
(4)thread(const thread&) = delete;
(1) 構造新的 thread 對象,但由於沒有傳入函數,所以thread對象還沒有關聯到線程。
(2) 移動構造函數。構造表示曾為 other 所表示的執行線程的 thread 對象。此調用后 other 不再表示執行線程。
(3) 構造新的 std::thread 對象並將它與執行線程關聯。新的執行線程開始執行。
(4) 復制構造函數被刪除, thread 不可復制。
下面我們來看一段代碼:
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 1 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10)); //毫秒級
// std::this_thread::sleep_for(std::chrono::seconds(1)); //秒級
}
}
void f2(int& n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
class foo
{
public:
void bar()
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 3 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int n = 0;
};
class baz
{
public:
void operator()()
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 4 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int n = 0;
};
int main()
{
int n = 0;
foo f;
baz b;
std::thread t1; // t1 不是線程
std::thread t2(f1, n + 1); // 按值傳遞
std::thread t3(f2, std::ref(n)); // 按引用傳遞
std::thread t4(std::move(t3)); // t4 現在運行 f2() 。 t3 不再是線程
std::thread t5(&foo::bar, &f); // t5 在對象 f 上運行 foo::bar()
std::thread t6(std::ref(b)); // t6 在對象 b 上運行 baz::operator()
t2.join();
t4.join();
t5.join();
t6.join();
std::cout << "Final value of n is " << n << '\n';
std::cout << "Final value of foo::n is " << f.n << '\n';
std::cout << "Final value of baz::n is " << b.n << '\n';
}
注意:若需要傳遞引用參數給線程函數,則必須包裝它 (例如用 std::ref 或 std::cref)。忽略來自函數的任何返回值。若函數拋異常,則調用 std::exception()。
觀察器
joinable
bool joinable() const noexcept;
用於判斷 thread 對象是否關聯到某一線程,若 thread 對象與執行線程關聯,則返回 true ,反之為 false 。
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::thread t;
std::cout << "before starting, joinable: " << std::boolalpha << t.joinable()
<< '\n';
t = std::thread(foo);
std::cout << "after starting, joinable: " << t.joinable()
<< '\n';
t.join();
std::cout << "after joining, joinable: " << t.joinable()
<< '\n';
}
輸出信息:
before starting, joinable: false
after starting, joinable: true
after joining, joinable: false
操作
join
void join();
阻塞當前線程直至 *this 所標識的線程結束其執行。*this 所標識的線程的完成同步於對應的從 join() 成功返回。*this 自身上不進行同步。同時從多個線程在同一 thread 對象上調用 join() 構成數據競爭,導致未定義行為。
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
// 模擬昂貴操作
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void bar()
{
// 模擬昂貴操作
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::cout << "starting first helper...\n";
std::thread helper1(foo);
std::cout << "starting second helper...\n";
std::thread helper2(bar);
std::cout << "waiting for helpers to finish..." << std::endl;
helper1.join();
helper2.join();
std::cout << "done!\n";
}
輸出信息:
starting first helper...
starting second helper...
waiting for helpers to finish...
done!
get_id
std::thread::id get_id() const noexcept;
返回標識與 *this 關聯的線程的 std::thread::id 。
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::thread t1(foo);
std::thread::id t1_id = t1.get_id();
std::thread t2(foo);
std::thread::id t2_id = t2.get_id();
std::cout << "t1's id: " << t1_id << '\n';
std::cout << "t2's id: " << t2_id << '\n';
t1.join();
t2.join();
}
t1's id: 0x35a7210f
t2's id: 0x35a311c4
detach
void detach();
從 thread 對象分離執行線程,允許執行獨立地持續。一旦該線程退出,則釋放任何分配的資源。調用 detach 后 *this 不再占有任何線程。
#include <iostream>
#include <chrono>
#include <thread>
void independentThread()
{
std::cout << "Starting concurrent thread.\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Exiting concurrent thread.\n";
}
void threadCaller()
{
std::cout << "Starting thread caller.\n";
std::thread t(independentThread);
t.detach();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Exiting thread caller.\n";
}
int main()
{
threadCaller();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
輸出信息:
Starting thread caller.
Starting concurrent thread.
Exiting thread caller.
Exiting concurrent thread.
swap
void swap( std::thread& other ) noexcept;
交換二個 thread 對象的底層柄。
#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void bar()
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
std::thread t1(foo);
std::thread t2(bar);
std::cout << "thread 1 id: " << t1.get_id() << '\n'
<< "thread 2 id: " << t2.get_id() << '\n';
std::swap(t1, t2);
std::cout << "after std::swap(t1, t2):" << '\n'
<< "thread 1 id: " << t1.get_id() << '\n'
<< "thread 2 id: " << t2.get_id() << '\n';
t1.swap(t2);
std::cout << "after t1.swap(t2):" << '\n'
<< "thread 1 id: " << t1.get_id() << '\n'
<< "thread 2 id: " << t2.get_id() << '\n';
t1.join();
t2.join();
}
輸出信息:
thread 1 id: 140185268262656
thread 2 id: 140185259869952
after std::swap(t1, t2):
thread 1 id: 140185259869952
thread 2 id: 140185268262656
after t1.swap(t2):
thread 1 id: 140185268262656
thread 2 id: 140185259869952
總結:
(0x01) std::thread 類創建線程非常方便,構造 thread 對象時傳入一個需要運行的函數及其參數。構造完成后,新的線程馬上被創建,同時執行該對象。注意:若需要傳遞引用參數給線程函數,則必須包裝它(例如用 std::ref 或 std::cref)。
(0x02) 使用 std::thread 默認的構造函數構造對象時,該對象是不關聯任何線程的。可以在之后的使用過程中再關聯到某一線程。可以通過使用 joinable() 接口,判斷一個 thread 對象是否關聯某個線程。
(0x03) 關聯到線程的 thread 對象析構前,必須調用 join() 接口等待線程結束。或者 thread 對象調用 detach() 接口解除與線程的關聯,否則會拋異常。
(0x04) thread 對象 detach() 后會獨立執行直至結束,而對應的 thread 對象變成不關聯任何線程的對象,joinable() 將返回 false。
(0x05) std::thread 沒有拷貝構造函數和拷貝賦值操作符,因此不支持復制操作(但從構造函數的示例代碼可以看出 std::thread 可以 move )。這也說明了沒有兩個 thread 對象可以表示同一執行線程。