c++怎么创建线程
导读:在C++中,可以使用 <thread> 库来创建线程。下面是一个简单的示例,展示了如何创建一个线程: #include <iostream> #include <thread> // 函数将在新线程中运...
在C++中,可以使用 <
thread>
库来创建线程。下面是一个简单的示例,展示了如何创建一个线程:
#include <
iostream>
#include <
thread>
// 函数将在新线程中运行
void print_hello() {
std::cout <
<
"Hello from thread!" <
<
std::endl;
}
int main() {
// 创建一个新线程并运行 print_hello 函数
std::thread t(print_hello);
// 在主线程中打印一条消息
std::cout <
<
"Hello from main thread!" <
<
std::endl;
// 等待新线程完成
t.join();
return 0;
}
在这个示例中,我们首先包含了 <
thread>
头文件。然后,我们定义了一个名为 print_hello
的函数,该函数将在新线程中运行。在 main
函数中,我们创建了一个名为 t
的 std::thread
对象,并将 print_hello
函数作为参数传递给它。这将导致 print_hello
函数在新线程中执行。
接下来,我们在主线程中打印一条消息。然后,我们使用 join()
方法等待新线程完成。最后,程序返回0并退出。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c++怎么创建线程
本文地址: https://pptw.com/jishu/708984.html