c++怎么创建一个多线程程序_c++多线程并发编程入门实例

C++中创建多线程依赖std::thread,需包含头文件,通过传递函数或lambda表达式启动线程,使用join()等待线程结束,多个线程可并发执行,共享数据时需用std::mutex和std::lock_guard保证线程安全。

在C++中创建多线程程序主要依赖于标准库中的 std::thread,从C++11开始,C++提供了对多线程的原生支持,无需引入第三方库(如pthread)。下面是一个简单的入门实例,帮助你理解如何使用C++编写多线程并发程序。

1. 包含头文件和启动线程

要使用多线程功能,需包含 thread 头文件。你可以将一个函数、lambda表达式或可调用对象传递给 std::thread 来创建新线程。

#include iostream>
#include

void hello() {
    std::cout }

int main() {
    std::thread t(hello); // 启动线程执行 hello 函数
    t.join(); // 等待线程结束
    return 0;
}

t.join() 表示主线程等待子线程执行完毕。如果不调用 join() 或 detach(),程序在主线程结束时会调用 std::terminate() 导致崩溃。

2. 使用 Lambda 创建线程

除了普通函数,还可以用 lambda 表达式创建线程,更加灵活。

#include stream>
#include

int main() {
    auto task = []() {
        std::cout     };
    std::thread t(task);
    t.join();
    return 0;
}

3. 多个线程并发执行

可以创建多个线程同时运行,实现并发。

#include
#include
#include

void print_id(int id) {
    std::cout }

int main() {
    std::vector<:thread> threads;

    // 创建10个线程
    for (int i = 0; i         threads.emplace_back(print_id, i);
    }

    // 等待所有线程完成
    for (auto& t : threads) {
        t.join();
    }

    return 0;
}

这里使用 std::vector<:thread> 存储多个线程对象,并通过 emplace_back 直接构造线程,传入函数和参数。

4. 注意线程安全与共享数据

当多个线程访问共享资源时,需要防止数据竞争。使用 std::mutex 加锁保护临界区。

#include
#include
#include
#include

std::mutex mtx;
int counter = 0;

void increment() {
    for (int i = 0; i         std::lock_guard<:mutex> lock(mtx);
        ++counter;
    }
}

int main() {
    std::vector<:thread> threads;
    for (int i = 0; i         threads.emplace_back(increment);
    }

    for (auto& t : threads) {
        t.join();
    }

    std::cout     return 0;
}

std::lock_guard 是RAII风格的锁管理,自动加锁和释放,避免死锁。

基本上就这些。掌握 thread、join、mutex 和 lock_guard 就能写出基础的C++多线程程序。不复杂但容易忽略细节,比如忘记 join 或没保护共享变量。