第五节 · 有条不紊 · 格式化输入输出

C++11 引入了线程支持库 <thread>,让多线程编程成为语言标准的一部分。


创建线程

#include <thread>

void task()
{
    cout << "Hello from thread!" << endl;
}

int main()
{
    // 创建并启动线程
    thread t(task);
    
    // 等待线程完成
    t.join();
    
    cout << "Main thread done" << endl;
    return 0;
}

传递参数


detach vs join


互斥锁


unique_lock


条件变量


原子操作


future 和 promise


并行算法(C++17)


线程安全的单例


习题

  • 实现一个线程池。

  • 编写生产者-消费者问题的完整解决方案。

  • 使用 future 实现并行计算斐波那契数列。

Last updated