阅读量:0
在Ubuntu中使用C++多线程,你需要使用C++11标准库中的头文件。以下是一个简单的示例,展示了如何在Ubuntu中使用C++多线程:
- 首先,确保你的编译器支持C++11或更高版本。在编译时,使用
-std=c++11或-std=c++14或-std=c++17等选项启用C++11支持。例如,如果你使用g++编译器,可以这样编译:
g++ -std=c++11 -pthread your_file.cpp -o your_program
注意:-pthread选项用于启用POSIX线程支持。
- 创建一个C++文件(例如
your_file.cpp),并包含头文件:
#include
#include
- 定义一个函数,该函数将在新线程中运行:
void my_function() {
std::cout << "Hello from the new thread!" << std::endl;
}
- 在
main()函数中,创建一个std::thread对象,并将你刚刚定义的函数作为参数传递给它:
int main() {
std::thread t(my_function);
- 使用
join()方法等待线程完成:
t.join();
return 0;
}
将以上代码片段组合在一起,你的完整C++程序应如下所示:
#include
#include
void my_function() {
std::cout << "Hello from the new thread!" << std::endl;
}
int main() {
std::thread t(my_function);
t.join();
return 0;
}
保存文件并使用g++编译器编译,然后运行生成的可执行文件。你应该会看到来自新线程的消息。
以上就是关于“如何在Ubuntu中使用C++多线程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm