C++ 11 thread 和基本线程同步

本文详细介绍了C++标准库中的多线程API,包括std::thread的构造、操作、观察器,以及std::mutex的基本同步和std::condition_variable的条件等待与通知。还通过生产者消费者模式展示了这些概念的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单记录一下多线程相关的 API

一 std::thread

std::thread 对象表示单个执行线程,通过给其传入一个任务函数来达到并发执行

1.构造函数

thread() noexcept;
// 默认构造函数,没有与之关联的执行线程
    
thread( thread&& other ) noexcept;
// 移动构造函数,移动后 other 不再表示执行线程

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
// 构造后执行线程开始执行,其中 f 为可调用对象,args为 f 的参数

thread( const thread& ) = delete;
// std::thread 只能移动,不能复制

std::thread 只能移动,不能复制

得到一个任务(函数)后立即创建线程并执行该任务

2.操作

void join();
// 阻塞当前线程直至 *this 所标识的线程结束其执行

void detach();
// 关联线程从 thread 对象分离,调用 detach 后 *this 不再占有这个关联线程。

void swap( std::thread& other ) noexcept;
// 交换两个 thread 对象的底层柄

3.观察器

bool joinable() const noexcept;
// thread 对象是否标识活跃的执行线程
// 默认构造的 thread 不可结合
// 结束执行代码,但仍未结合的线程仍被当作活跃的执行线程,从而可结合
// join() 和 detach() 后不可结合

std::thread::id get_id() const noexcept;
// 返回标识与 *this 关联的线程的 std::thread::id 

4.std::thread 对象创建

(1)函数指针

void myFunction() {
   
    // 执行的任务
}

int main() {
   
    std::thread myThread(myFunction);  // 使用函数指针创建线程
    // ...
    return 0;
}

(2)函数对象

struct MyFunctor {
   
    void operator()() {
   
        // 执行的任务
    }
};

int main() {
   
    MyFunctor functor;
    std::thread myThread(functor)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值