C++11 在 Windows 环境下的多线程编程指南

news/2024/10/18 14:23:12/

引言

随着多核处理器的普及,利用多线程编程来提升应用程序性能变得越来越重要。C++11 标准库引入了一系列用于多线程编程的API,使得多线程编程变得更加简洁和高效。

一、基本概念

在开始编写多线程代码之前,了解一些基本概念是非常重要的:

  1. 线程:线程是操作系统能够调度的最小执行单元。一个进程可以包含多个线程,这些线程共享进程的资源,但可以独立执行。
  2. 并行和并发:并行是指多个线程同时执行,而并发是指多个线程在同一时间段内交替执行。

二、创建和管理线程

C++11标准库提供了std::thread类来创建和管理线程。我们可以通过以下几种方式创建线程:

1. 创建线程

(1)使用函数指针
#include <iostream>
#include <thread>void threadFunction() {std::cout << "Hello from thread!\n";
}int main() {std::thread t(threadFunction);t.join(); // 等待线程t完成return 0;
}

(2)使用lambda表达式

#include <iostream>
#include <thread>int main() {std::thread t([]{std::cout << "Hello from lambda thread!\n";});t.join();return 0;
}

(3)使用成员函数

#include <iostream>
#include <thread>class MyClass {
public:void memberFunction() {std::cout << "Hello from member function thread!\n";}
};int main() {MyClass obj;std::thread t(&MyClass::memberFunction, &obj);t.join();return 0;
}

2. 线程同步

在多线程编程中,同步是一个关键问题,C++11 提供了多种同步机制,包括互斥量(std::mutex)、锁(std::lock_guardstd::unique_lock)、条件变量(std::condition_variable)等。

(1)互斥量

互斥量用于保护共享数据,防止数据竞争。

#include <iostream>
#include <thread>
#include <mutex>std::mutex mtx;void printMessage(const std::string& msg) {std::lock_guard<std::mutex> lock(mtx);std::cout << msg << std::endl;
}int main() {std::thread t1(printMessage, "Hello from thread 1");std::thread t2(printMessage, "Hello from thread 2");t1.join();t2.join();return 0;
}
(2)条件变量

条件变量用于线程间的通知机制。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>std::mutex mtx;
std::condition_variable cv;
bool ready = false;void printMessage() {std::unique_lock<std::mutex> lock(mtx);cv.wait(lock, []{ return ready; });std::cout << "Thread is running!\n";
}int main() {std::thread t(printMessage);{std::lock_guard<std::mutex> lock(mtx);ready = true;}cv.notify_one();t.join();return 0;
}

3. 线程局部存储

C++11 提供了 thread_local 关键字,用于定义线程局部变量。

#include <iostream>
#include <thread>thread_local int threadId = 0;void printThreadId(int id) {threadId = id;std::cout << "Thread ID: " << threadId << std::endl;
}int main() {std::thread t1(printThreadId, 1);std::thread t2(printThreadId, 2);t1.join();t2.join();return 0;
}

4. 其他API

(1)std::async 和 std::future

std::async 用于异步执行任务,并返回一个 std::future 对象,用于获取异步任务的结果。

#include <iostream>
#include <future>int asyncFunction() {return 42;
}int main() {std::future<int> result = std::async(std::launch::async, asyncFunction);std::cout << "Async result: " << result.get() << std::endl;return 0;
}
(2)std::packaged_task

std::packaged_task 也用于异步执行任务,但它允许将任务包装成一个可调用对象,并与 std::future 关联。

#include <iostream>
#include <future>int taskFunction() {return 42;
}int main() {std::packaged_task<int()> task(taskFunction);std::future<int> result = task.get_future();std::thread(std::move(task)).detach();std::cout << "Task result: " << result.get() << std::endl;return 0;
}

三、总结

C++11 标准库提供了一套强大而简洁的多线程编程API,极大地简化了多线程编程的复杂性。通过 std::thread 类,我们可以方便地创建和管理线程;通过互斥量和条件变量等同步机制,我们可以有效地避免数据竞争;通过 std::asyncstd::future 等工具,我们可以轻松地实现异步编程。这些工具不仅适用于Windows环境,也适用于其他平台,使得我们的代码具有良好的可移植性。

更多详细代码:C++11多线程编程: Windows下C++11多线程编程


http://www.ppmy.cn/news/1466212.html

相关文章

linux学习:进程通信 管道

目录 例子1 父进程向子进程发送一条消息&#xff0c;子进程读取这条消息 例子2 mkfifo 函数创建一个命名管道 例子3 mkfifo 函数创建一个命名管道处理可能出现的错误 例子4 管道文件是否已存在 例子5 除了“文件已存在”进行处理 例子6 创建一个命名管道&…

2024年最适合中小型企业的顶级12款CRM系统对比

适合中小企业的CRM系统包括&#xff1a;纷享销客、Zoho CRM、HubSpot CRM、Freshsales、Pipedrive、Monday Sales CRM、Salesmate、Capsule CRM、金蝶云CRM、用友CRM、有赞CRM、简信CRM。 在现代商业运营中&#xff0c;CRM&#xff08;客户关系管理&#xff09;系统已成为不可或…

小白跟做江科大32单片机之旋转编码器计次

原理部分按照下面这个链接理解即可y小白跟做江科大32单片机之对射式红外传感器计次-CSDN博客https://blog.csdn.net/weixin_58051657/article/details/139350487https://blog.csdn.net/weixin_58051657/article/details/139350487 实验过程 1.按照江科大老师给的电路图进行连接…

MySQL Doublewrite Buffer 有了解过吗?

引言&#xff1a;在数据库管理中&#xff0c;确保数据的完整性和一致性是至关重要的。然而&#xff0c;在持久化数据到磁盘的过程中&#xff0c;可能会遇到各种意外情况&#xff0c;如断电或系统崩溃&#xff0c;从而导致部分数据写入&#xff0c;而另一部分数据未能成功写入&a…

数据结构 实验 1

题目一&#xff1a;用线性表实现文具店的货品管理问题 问题描述&#xff1a;在文具店的日常经营过程中&#xff0c;存在对各种文具的管理问题。当库存文具不足或缺货时&#xff0c;需要进货。日常销售时需要出库。当盘点货物时&#xff0c;需要查询货物信息。请根据这些要求编…

eNSP——两台电脑通过一根网线直连通信

一、拓扑结构 二、电脑配置 ip和子网掩码&#xff0c;配置两台电脑处于同一网段 三、测试 四、应用 传文件等操作&#xff0c;可以在一台电脑上配置FTP服务器

PyTorch、显卡、CUDA 和 cuDNN 之间的关系

概述 PyTorch、显卡、CUDA 和 cuDNN 之间的关系及其工作原理可以这样理解&#xff1a; 显卡 (GPU) 显卡&#xff0c;特别是 NVIDIA 的 GPU&#xff0c;具有大量的并行处理单元&#xff0c;这些单元可以同时执行大量相似的操作&#xff0c;非常适合进行大规模矩阵运算&#x…

数据结构复习指导之交换排序(冒泡排序,快速排序)

目录 交换排序 复习提示 1.冒泡排序 1.1基本思想 1.2算法代码 1.3性能分析 2.快速排序 2.1基本思想 2.2算法代码 2.3性能分析 交换排序 复习提示 所谓交换&#xff0c;是指根据序列中两个元素关键字的比较结果来对换这两个记录在序列中的位置。 基于交换的排序算法很…