一、作用:
构造thread对象时,传入一个可调用对象作为参数(如果可调用对象有参数,把参数同时传入)。这样构造完成后,新的线程马上被创建,同时执行该可调用对象。
二、用法:
2.1、std::thread::join
A线程调用B线程对象的join函数后,阻止A线程的执行,直到B线程对应可调用对象的所有操作执行完成。
2.2、std::thread::joinable
检查对应线程对象是否可以调用join函数。
true的场景: 以可调用对象构造
false的场景: 默认构建、调用join或detach之后的线程对象。
2.3、std::thread::detach
将对象表示的线程与调用线程分离,允许它们彼此独立执行。
2.4、std::thread::get_id
获取线程ID,返回值类型为thread::id,转换为string/int类型方式:
转成string:
#include <sstream>
auto myid = this_thread::get_id();
stringstream ss;
ss << myid;
string mystring = ss.str();
转成int:
int x = stoi(mystring);
参考资料: Linux下获取线程ID
注:在字符串mystring
过长时,stoi
函数会抛出异常导致程序挂掉,因此需要做容错处理,或者线程ID只按字符串输出。
参考资料:C++11中stoi函数的异常处理
2.5、线程睡眠一定时长:
std::this_thread::sleep_for(std::chrono::seconds(1));
三、案例:
// 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;
}