阅读量:2
在Ubuntu上进行C++多线程编程,你需要使用C++11标准库中的头文件。以下是一个简单的示例,展示了如何在Ubuntu上使用C++11的线程功能:
-
首先,确保你的编译器支持C++11或更高版本。在编译时,使用
-std=c++11或-std=c++14或-std=c++17等选项来启用C++11特性。 -
创建一个名为
multithreading_example.cpp的文件,并添加以下代码:
#include
#include
// 线程函数
void hello_thread() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 创建一个线程对象,将hello_thread函数作为参数传递
std::thread t(hello_thread);
// 等待线程完成
t.join();
std::cout << "Hello from the main thread!" << std::endl;
return 0;
}
- 使用以下命令编译代码:
g++ -std=c++11 multithreading_example.cpp -o multithreading_example
- 运行生成的可执行文件:
./multithreading_example
你应该会看到以下输出:
Hello from a thread!
Hello from the main thread!
这个示例展示了如何在Ubuntu上使用C++11的线程功能创建一个简单的多线程程序。你可以根据需要修改hello_thread函数以实现更复杂的多线程功能。
以上就是关于“Ubuntu上C++多线程编程怎样实现”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm