本文主要是介绍std :: thread,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
头文件<thread>中包含两个类,thread和this_thread
在讲thread之前,首先要了解线程的一个状态:joinable
一个正规初始化后的线程是一个可执行线程,这种线程joinable为true,并且有一个独一无二的线程id。
相反,一个默认构造函数构造出的thread(thread(),没有参数,未初始化),joinable为false,且线程id通常和其他所有的non-joinable线程一样。
一个joinable线程被move from,或者调用join,detach后,变成non-joinable
1、成员类型
id | |
native_handle_type |
2、成员函数
constructor |
| ||||||||
destructor | 如果该线程是joinable,则调用terminate() | ||||||||
operator= |
| ||||||||
get_id | Returns the thread id. | ||||||||
joinable | check if joinable | ||||||||
join | Join thread | ||||||||
detach | Detach thread | ||||||||
swap | |||||||||
native_handle | Get native handle | ||||||||
hardware_concurrency [static] | Detect hardware concurrency |
3、非成员函数(重载)
swap
4、代码示例
// thread example
#include <iostream> // std::cout
#include <thread> // std::threadvoid 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 finishessecond.join(); // pauses until second finishesstd::cout << "foo and bar completed.\n";return 0;
}
输出结果
main, foo and bar now execute concurrently...
foo and bar completed.
这篇关于std :: thread的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!