c++如何实现多线程编程_c++多线程实现方法

21次阅读

c++线程编程依赖std::Thread,通过函数、Lambda创建线程,需调用join或detach;使用mutex和lock_guard防止数据竞争;async与future获取异步结果;condition_variable配合锁实现线程安全队列,避免死锁与竞态。

c++如何实现多线程编程_c++多线程实现方法

C++ 实现多线程编程主要依赖标准库中的 std::thread,从 C++11 开始,语言原生支持多线程,无需依赖第三方库或平台特定 API。下面介绍几种常用的 C++ 多线程实现方法,帮助你快速上手并避免常见问题

使用 std::thread 创建线程

最基础的方式是通过 std::thread 启动一个新线程。你可以传入函数、lambda 表达式或可调用对象

  • 启动线程后,必须调用 join() 等待其结束,或 detach() 让其在后台运行
  • 未 join 或 detach 的线程在析构时会调用 std::terminate()

示例代码:

#include <thread> #include <iostream> <p>void say_hello() { std::cout << "Hello from thread!" << std::endl; }</p><p>int main() { std::thread t(say_hello); t.join(); // 等待线程结束 return 0; }

线程间共享数据与同步

多个线程访问共享资源时容易出现数据竞争。C++ 提供了互斥量(mutex)来保护临界区。

立即进入豆包AI人工智官网入口”;

立即学习豆包AI人工智能在线问答入口”;

  • 使用 std::mutex 配合 std::lock_guard 实现自动加锁解锁
  • 避免死锁:多个线程以相同顺序获取多个锁

示例:保护共享变量

c++如何实现多线程编程_c++多线程实现方法

豆包AI编程

豆包推出的AI编程助手

c++如何实现多线程编程_c++多线程实现方法483

查看详情 c++如何实现多线程编程_c++多线程实现方法

#include <thread> #include <mutex> #include <iostream> <p>int counter = 0; std::mutex mtx;</p><p>void increment() { for (int i = 0; i < 1000; ++i) { std::lock_guard<std::mutex> lock(mtx); ++counter; } }</p><p>int main() { std::thread t1(increment); std::thread t2(increment);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">t1.join(); t2.join();  std::cout << "Counter: " << counter << std::endl; // 输出 2000 return 0;

}

使用 std::async 和 std::future 获取返回值

当你需要从线程中获取计算结果时,可以使用 std::async 启动异步任务,并通过 std::future 获取结果。

  • std::async 可能创建新线程,也可能在等待时同步执行(取决于策略)
  • future.get() 会阻塞直到结果就绪

示例:异步计算平方

#include <future> #include <iostream> <p>int square(int x) { return x * x; }</p><p>int main() { std::future<int> result = std::async(square, 5); std::cout << "Result: " << result.get() << std::endl; // 输出 25 return 0; }

线程安全的队列与生产者-消费者模型

实际项目中常使用任务队列配合线程池。一个典型的模式是多个线程从共享队列取任务执行。

  • 队列操作需加锁
  • 使用 condition_variable 实现线程等待/通知机制

简化版线程安全队列:

#include <queue> #include <mutex> #include <condition_variable> <p>template<typename T> class SafeQueue { private: std::queue<T> data; std::mutex mtx; std::condition_variable cv;</p><p>public: void push(T val) { std::lock_guard<std::mutex> lock(mtx); data.push(val); cv.notify_one(); }</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">T pop() {     std::unique_lock<std::mutex> lock(mtx);     cv.wait(lock, [this]{ return !data.empty(); });     T val = data.front();     data.pop();     return val; }

};

基本上就这些核心方法。掌握 thread、mutex、future 和 condition_variable 就能应对大多数多线程场景。注意避免死锁、资源泄漏和竞态条件,多线程编程的关键在于设计清晰的同步逻辑。不复杂但容易忽略细节。

text=ZqhQzanResources