文章目录
- 创建线程
- 传递参数
- 等待线程完成
- 分离线程
- joinable()
创建线程
要创建线程,我们需要一个可调用的函数或函数对象,作为线程的入口点。在C++11中,我们可以使用函数指针、函数对象或lambda表达式来实现。
(图片来源网络,侵删)创建线程的基本语法如下:
#include //头文件 using namespace std; thread t(function_name, args...); `function_name`是线程入口点的函数或可调用对象 `args...`是传递给函数的参数
创建线程后,我们可以使用t.join()等待线程完成,或者使用t.detach()分离线程,让它在后台运行。
(图片来源网络,侵删)#include #include using namespace std; void print_message() { cout std::thread t(print_message); t.join(); return 0; } cout ++x; } int main() { string message = "Hello, world!"; thread t(print_message, message); t.join(); int x = 0; thread t2(increment, ref(x)); t2.join(); cout std::cout thread t1(print_message, "Thread 1"); thread t2(print_message, "Thread 2"); t1.join(); t2.join(); cout cout thread t(print_message, "Thread 1"); t.detach(); cout cout thread t(foo); if (t.joinable()) { t.join(); } cout