ubuntu

Ubuntu下C++多线程怎么实现

小樊
44
2025-04-02 09:07:06
栏目: 编程语言

在Ubuntu下使用C++实现多线程,你可以使用C++11标准库中的<thread>头文件。下面是一个简单的示例,展示了如何创建和使用多个线程。

首先,确保你的编译器支持C++11或更高版本。在编译时,使用-std=c++11-std=c++14-std=c++17等选项来启用C++11特性。

#include <iostream>
#include <thread>

// 线程函数
void helloThread(int threadId) {
    std::cout << "Hello from thread " << threadId << std::endl;
}

int main() {
    // 创建两个线程
    std::thread t1(helloThread, 1);
    std::thread t2(helloThread, 2);

    // 等待线程完成
    t1.join();
    t2.join();

    std::cout << "All threads finished." << std::endl;

    return 0;
}

编译并运行这个程序:

g++ -std=c++11 -pthread your_file.cpp -o your_program
./your_program

这个示例中,我们定义了一个名为helloThread的线程函数,它接受一个整数参数threadId。在main函数中,我们创建了两个线程t1t2,并将它们分别传递给helloThread函数。然后,我们使用join()方法等待这两个线程完成。最后,程序输出"All threads finished."。

注意:在使用<thread>库时,需要在编译命令中添加-pthread选项,以便链接线程库。

这只是一个简单的示例,C++11线程库还提供了许多其他功能,如互斥锁(std::mutex)、条件变量(std::condition_variable)和原子操作(std::atomic)等,以帮助你实现更复杂的多线程程序。

0
看了该问题的人还看了