在Ubuntu中,C++的多线程可以通过C++11标准库中的<thread>
头文件来实现。以下是一个简单的示例,展示了如何在C++中使用多线程:
#include <iostream>
#include <thread>
// 线程函数
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 创建一个线程对象,将helloFunction作为参数传递给它
std::thread t(helloFunction);
// 等待线程完成
t.join();
std::cout << "Hello from the main thread!" << std::endl;
return 0;
}
要编译这个程序,请确保使用支持C++11或更高版本的编译器,并在编译命令中添加-std=c++11
标志。例如,如果你使用g++编译器,可以使用以下命令:
g++ -std=c++11 -o my_program my_program.cpp
然后运行生成的可执行文件:
./my_program
这将创建一个新线程,该线程将执行helloFunction
函数,同时在主线程中输出"Hello from the main thread!"。注意,由于线程的执行顺序是不确定的,因此输出的顺序可能会有所不同。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Ubuntu C++多线程怎么实现