简单示例
#include <iostream>
#include <thread>
void hello() {
std::cout << "hello world" << std::endl;
}
int main() {
std::thread t(hello);
t.join();
}
编译命令:
g++ -std=c++11 hello.cpp -o hello -pthread
C++支持多线程,有三点注意:
- 包含头文件
#include <thread> - 编译选项
-std=c++11 - 编译选项
-pthread
不添加编译选项-pthread,则运行出现Enable multithreading to use std::thread: Operation not permitted。
选项中指定-lpthread和-pthread一样,建议使用-pthread。
这篇博客介绍了C++中实现多线程的基本步骤,包括包含`<thread>`头文件,使用`-std=c++11`编译选项以及添加`-pthread`选项。示例代码展示了如何创建并运行一个简单的线程。在不添加`-pthread`选项时,程序会报错。文章强调了正确编译设置对于启用多线程支持的重要性。
1003

被折叠的 条评论
为什么被折叠?



