linux

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

小樊
60
2025-06-19 20:05:55
栏目: 编程语言

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

#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的编译器,如g++。在命令行中,使用以下命令编译:

g++ -std=c++11 -pthread your_file_name.cpp -o output_file_name

这里,-std=c++11表示使用C++11标准,-pthread表示启用多线程支持。

运行编译后的程序,你将看到两个线程的输出:

Hello from a thread!
Hello from the main thread!

注意,线程的执行顺序是不确定的,因此输出的顺序可能会有所不同。

如果你需要在多个线程之间共享数据,可以使用std::mutexstd::lock_guard来保护共享数据,以避免竞争条件。以下是一个简单的示例:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx; // 创建一个互斥锁

void increment(int& value) {
    mtx.lock(); // 锁定互斥锁
    ++value; // 修改共享数据
    mtx.unlock(); // 解锁互斥锁
}

int main() {
    int shared_value = 0;

    // 创建两个线程,它们都将调用increment函数
    std::thread t1(increment, std::ref(shared_value));
    std::thread t2(increment, std::ref(shared_value));

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

    std::cout << "Shared value: " << shared_value << std::endl;

    return 0;
}

这个程序将输出:

Shared value: 2

这里,我们使用了std::ref来传递共享变量的引用,以便在线程之间共享数据。

0
看了该问题的人还看了