【C++】线程(thread)

std::thread是C++11标准库中用于创建和管理线程的类。它提供了一种简单且高效的方式来创建和管理多线程应用程序。以下是对std::thread的详细介绍,以及一些示例代码。

创建线程

使用std::thread创建线程非常简单,只需要将要在新线程中执行的函数(或可调用对象)传递给std::thread的构造函数:

#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Thread is running." << std::endl;
}

int main() {
    std::thread t(threadFunction); // 创建并启动线程
    t.join(); // 等待线程完成
    return 0;
}

传递参数给线程

可以通过构造函数将参数传递给线程函数:

#include <iostream>
#include <thread>

void threadFunction(int n) {
    std::cout << "Thread received parameter: " << n << std::endl;
}

int main() {
    std::thread t(threadFunction, 5); // 创建并启动线程,同时传递参数
    t.join(); // 等待线程完成
    return 0;
}

使用lambda表达式创建线程

还可以使用lambda表达式来创建线程:

#include <iostream>
#include <thread>

int main() {
    std::thread t([] {
        std::cout << "Thread is running using lambda." << std::endl;
    });
    t.join(); // 等待线程完成
    return 0;
}

线程分离与合并

  • 线程分离:使线程在后台运行,主线程不等待其完成。
  • 线程合并:等待线程完成。
#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Thread is running." << std::endl;
}

int main() {
    std::thread t(threadFunction);

    // 分离线程
    t.detach();
    // 或者等待线程完成
    // t.join();

    std::cout << "Main thread is exiting." << std::endl;
    return 0;
}

线程可移动但不可复制

std::thread对象是不可复制的,但可以通过移动构造或移动赋值操作符将其移动:

#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Thread is running." << std::endl;
}

int main() {
    std::thread t1(threadFunction);
    std::thread t2 = std::move(t1); // 移动线程对象
    t2.join(); // 等待线程完成

    return 0;
}

使用互斥锁保护共享数据

在多线程编程中,访问共享数据时需要使用互斥锁来防止数据竞争:

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

std::mutex mtx;

void printMessage(const std::string& message, int count) {
    for (int i = 0; i < count; ++i) {
        std::lock_guard<std::mutex> lock(mtx);
        std::cout << message << ": " << i << std::endl;
    }
}

int main() {
    std::thread t1(printMessage, "Thread 1", 5);
    std::thread t2(printMessage, "Thread 2", 5);

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

    return 0;
}

在这个示例中,使用std::mutexstd::lock_guard来保护共享的标准输出流,防止多个线程同时访问它而导致的竞争条件。

总结

std::thread是C++11引入的强大工具,极大简化了多线程编程。它提供了灵活和高效的方式来创建、管理和同步线程,使开发者能够轻松实现并发编程。但在使用多线程时,必须小心处理共享数据,避免竞争条件和死锁等问题。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值