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;
}
参考资料: std::thread
2、常用函数解释:
1、std::thread::join: 将该函数返回的时刻与该对象表示的线程所有操作执行完成的时间同步;同时阻止调用此函数的线程的执行,直到该线程执行完成。
2、std::thread::detach: 将对象表示的线程与调用线程分离,允许它们彼此独立执行。
参考资料:http://www.cplusplus.com/reference/thread/thread/detach/
3、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);
注:在字符串mystring过长时,stoi函数会抛出异常导致程序挂掉,因此需要做容错处理,或者线程ID只按字符串输出。
参考资料:
1、Linux下获取线程ID
2、C++11中stoi函数的异常处理
4、线程睡眠一定时长:
std::this_thread::sleep_for(std::chrono::seconds(1));