C++ 创建线程
时间: 2023-08-12 11:21:35 浏览: 43
在 C++ 中创建线程可以使用标准库中的 `<thread>` 头文件。下面是一个简单的例子:
```c++
#include <iostream>
#include <thread>
void printMessage() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(printMessage); // 创建一个新线程并运行 printMessage 函数
t.join(); // 等待线程执行完毕
return 0;
}
```
在上面的代码中,`std::thread` 构造函数接受一个函数指针作为参数,表示新线程将要执行的函数。然后通过 `t.join()` 等待线程执行完毕。
注意,如果新线程执行的函数需要传递参数,可以在构造函数中将参数传递给函数。例如:
```c++
#include <iostream>
#include <thread>
void printMessage(const std::string& message) {
std::cout << message << std::endl;
}
int main() {
std::string message = "Hello from thread!";
std::thread t(printMessage, message); // 将 message 作为参数传递给 printMessage 函数
t.join();
return 0;
}
```