C++多线程编程通过std::thread实现,支持函数、Lambda创建线程,可传值或引用参数,需调用join()或detach()管理线程生命周期,并可使用hardware_concurrency()获取硬件并发数。

C++ 实现多线程编程主要通过标准库中的 std::thread 来完成。从 C++11 开始,C++ 标准提供了对多线程的原生支持,使得开发者无需依赖第三方库(如 pthread)也能轻松编写跨平台的多线程程序。
创建和启动线程
使用 std::thread 可以通过函数、函数对象、Lambda 表达式等方式创建线程。
基本语法:
- 包含头文件:
#include - 构造一个 thread 对象并传入可调用目标
#include <iostream>
#include <thread>
void say_hello() {
std::cout <font color="green">示例2:使用 Lambda 表达式</font><pre class="brush:php;toolbar:false;">#include <iostream>
#include <thread>
int main() {
std::thread t([](){
std::cout <h3>传递参数给线程函数</h3>
<p>向线程函数传递参数时,需在构造 thread 对象时一并传入。注意:默认是值传递,若要引用传递,必须使用 <strong>std::ref</strong>。</p>
<font color="green">示例:传参与引用传递</font><pre class="brush:php;toolbar:false;">#include <iostream>
#include <thread>
void print_num(int n, std::string& msg) {
n += 10;
msg += " (modified)";
std::cout <p>输出中可以看到,<code>val</code> 的修改在线程内无效(值传递),而 <code>str</code> 被修改了(引用传递)。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13058" title="Upstream Recon"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Upstream Recon" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13058" title="Upstream Recon" class="overflowclass">Upstream Recon</a>
<p class="overflowclass">在与开源项目(如提交PR、Issue或评论)互动前,先对其进行调研。适用于:提交Issue、提交PR或发表评论之前。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13058" title="Upstream Recon" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<h3>线程的等待与分离</h3>
<p>每个 thread 对象有两种运行模式:</p>
<ul>
<li>
<strong>join()</strong>:主线程等待该线程执行完毕</li>
<li>
<strong>detach()</strong>:线程与主线程分离,独立运行(后台运行)</li>
</ul>
<p>必须在 thread 对象销毁前调用其中之一,否则程序会终止(调用 std::terminate)。</p>
<font color="green">示例:分离线程</font><pre class="brush:php;toolbar:false;">#include <iostream>
#include <thread>
#include <chrono>
void background_task() {
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout <h3>获取硬件支持的并发线程数</h3>
<p>可以使用 <strong>std::thread::hardware_concurrency()</strong> 查询系统建议的最大并发线程数。</p>
<pre class="brush:php;toolbar:false;">unsigned int max_threads = std::thread::hardware_concurrency();
std::cout <p>这个值只是一个提示,可能返回 0(表示无法确定)。</p><p>
基本上就这些。掌握 std::thread 的创建、参数传递、生命周期管理,就能应对大多数基础多线程场景。实际开发中常配合 mutex、条件变量等<a style="color:#f60; text-decoration:underline;" title="同步机制" href="https://m.php.cn/zt/57778.html" target="_blank">同步机制</a>使用,避免数据竞争。</p>
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










