在Ubuntu中使用C++多线程,你需要使用C++11标准库中的<thread>
头文件。以下是一个简单的示例,展示了如何在Ubuntu中使用C++多线程:
-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线程支持。
your_file.cpp
),并包含<thread>
头文件:#include <iostream>
#include <thread>
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 <iostream>
#include <thread>
void my_function() {
std::cout << "Hello from the new thread!" << std::endl;
}
int main() {
std::thread t(my_function);
t.join();
return 0;
}
保存文件并使用g++编译器编译,然后运行生成的可执行文件。你应该会看到来自新线程的消息。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 为什么选择Ubuntu作为LAMP服务器