std::thread在<thread>头文件中声明,因此使用std::thread时包含<thread>头文件
1、std::thread构造:
1)default——thread():默认构造函数,创建一个空的thread执行对象
2)initialization——thread(a,b):初始化构造函数,创建一个thread对象,该对象可被joinable,新产生的线程会调用a函数,函数的参数由b给出
3)copy[deleted]——thread(const thread& ) = delete:拷贝构造函数禁用,意味着thread不可被拷贝构造
4)move——thread(thread&& x)noexcept:构造函数,调用成功后x不代表任何thread执行对象
注意:可被joinable的thread对象必须在它们销毁之前被主线程join,或者将其设置为detached
std::thread各种构造函数例子如下:
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
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));
}
}
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));
}
}
int main()
{
int n = 0;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + 1); // pass by value
std::thread t3(f2, std::ref(n)); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
t2.join();
t4.join();
std::cout << "Final value of n is " << n << '\n';
}
在Mac下打印结果是这样的
TThhrreeaadd 21 executing
executing
TThhrreeaadd 21 executing
executing
Thread 1 executing
Thread 2 executing
TThhrreeaadd 12 eexxeeccuuttiinngg
Thread 1 executing
Thread 2 executing
Final value of n is 5
2、Move赋值操作
1)move——thread& operator=(thread&& rh
s) noexcept;move赋值操作,如果当前对象不可joinable,需要传递一个右值引用给move赋值操作,如果当前对象可被joinable,则terminate()报错。
2)copy[deleted]——thread& operator=(const thread&) = delete;拷贝赋值操作被禁用,thread对象不可被拷贝
#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
void thread_task(int n)
{
this_thread::sleep_for(chrono::seconds(n));
cout << "hello thread " << this_thread::get_id() << " Pause " << n << " seconds" << endl;
}
int main(void)
{
std::thread threads[5];
cout << "Spawning 5 threads...\n";
for(int i = 0;i < 5; i++)
{
threads[i] = std::thread(thread_task,i+1);
}
cout << "Done spawning threads! Now wait for them to join\n";
for(auto& t : threads)
{
t.join();
}
cout << "All threads joined.\n";
return EXIT_SUCCESS;
}
3、其它成员函数
1)get_id:获取线程ID
2)joinable:检测线程是否可被join
3)join:join线程,会和主线程
4)detach:detach线程,与主线程分离
5)swap:swap线程
6)native_handle:返回native_handle
7)hardware_concurrency[static]:检测硬件并发特性