如何在Ubuntu中使用C++多线程

849
2025/3/23 9:32:03
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu中使用C++多线程,你需要使用C++11标准库中的<thread>头文件。以下是一个简单的示例,展示了如何在Ubuntu中使用C++多线程:

  1. 首先,确保你的编译器支持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线程支持。

  1. 创建一个C++文件(例如your_file.cpp),并包含<thread>头文件:
#include <iostream>
#include <thread>
  1. 定义一个函数,该函数将在新线程中运行:
void my_function() {
    std::cout << "Hello from the new thread!" << std::endl;
}
  1. main()函数中,创建一个std::thread对象,并将你刚刚定义的函数作为参数传递给它:
int main() {
    std::thread t(my_function);
  1. 使用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服务器