#include <iostream>
#include <thread>
// 定义一个简单的函数,将在新线程中执行
void printNumbers() {
for (int i = 0; i < 5; ++i) {
std::cout << "Number: " << i << std::endl;
}
}
int main() {
// 创建一个线程来执行 printNumbers 函数
std::thread t(printNumbers);
// 主线程继续执行其他任务
for (int i = 0; i < 5; ++i) {
std::cout << "Main thread: " << i << std::endl;
}
// 等待子线程完成
if (t.joinable()) {
t.join(); // 调用 join 等待线程结束
}
return 0;
}
#include <thread>
引入了 C++ 标准库中的线程支持。printNumbers
是一个普通的函数,它将在新线程中执行,打印一些数字。std::thread t(printNumbers);
创建了一个新的线程 t
,该线程会执行 printNumbers
函数。if (t.joinable()) { t.join(); }
检查线程是否可以 join(即是否已经启动且未 join),然后调用 join
等待子线程完成。这确保了主线程不会在子线程完成之前退出程序。这段代码展示了如何在 C++ 中使用多线程来并行执行任务。
上一篇:c++ boost
下一篇:sort函数c++用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站