商城首页欢迎来到中国正版软件门户

您的位置:首页 >C++多线程创建与同步实例解析

C++多线程创建与同步实例解析

  发布于2025-11-04 阅读(0)

扫一扫,手机访问

C++中使用std::thread可直接创建多线程,通过函数、lambda或可调用对象启动线程,支持参数传递(引用需用std::ref),并可用std::mutex和std::lock_guard实现线程同步,确保共享数据安全。

c++中如何使用std::thread创建多线程程序_c++多线程创建与同步示例

在C++中使用std::thread创建多线程程序非常直接。从C++11开始,标准库提供了<thread>头文件,支持跨平台的多线程编程。下面介绍如何创建线程、传递参数、以及简单的线程同步方法。

创建基本线程

要启动一个新线程,只需将函数名或可调用对象传入std::thread构造函数。

示例:

#include <iostream>
#include <thread>

void say_hello() {
    std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}

int main() {
    std::thread t(say_hello);  // 启动线程
    std::cout << "Main thread running." << std::endl;
    t.join();  // 等待线程结束
    return 0;
}

说明:

  • t.join() 表示主线程等待子线程执行完毕。
  • 如果不调用join()detach(),程序在thread对象析构时会调用std::terminate()终止程序。

向线程传递参数

可以通过额外参数将数据传入线程函数。注意:默认是按值传递,若需引用,必须使用std::ref

#include <iostream>
#include <thread>

void print_number(int& n) {
    n += 10;
    std::cout << "Thread: n = " << n << std::endl;
}

int main() {
    int num = 5;
    std::thread t(print_number, std::ref(num));  // 使用std::ref传引用
    t.join();
    std::cout << "Main: num = " << num << std::endl;  // 输出15
    return 0;
}

注意:如果传指针或值,不需要std::ref;只有引用类型才需要。

使用lambda表达式创建线程

Lambda让线程代码更灵活,尤其适合短小逻辑。

#include <iostream>
#include <thread>

int main() {
    auto task = []() {
        std::cout << "Lambda thread running." << std::endl;
    };

    std::thread t(task);
    t.join();
    return 0;
}

线程同步:使用互斥锁(mutex)

多个线程访问共享数据时,需防止竞争条件。常用std::mutexstd::lock_guard保护临界区。

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

std::mutex mtx;
int shared_counter = 0;

void increment() {
    for (int i = 0; i < 100000; ++i) {
        std::lock_guard<std::mutex> lock(mtx);  // 自动加锁/解锁
        ++shared_counter;
    }
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);

    t1.join();
    t2.join();

    std::cout << "Final counter value: " << shared_counter << std::endl;
    return 0;
}

说明:

  • std::lock_guard在构造时加锁,析构时自动释放,避免死锁。
  • 即使函数抛出异常,也能保证锁被释放。

基本上就这些。掌握std::thread、参数传递和std::mutex后,就能写出基本的安全多线程程序。实际开发中还可结合std::atomicstd::condition_variable等工具实现更复杂的同步逻辑。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注