当前位置: 首页 > news >正文

C++线程库

1. 基本概念

1.1 线程(Thread)

线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一个进程可以并发多个线程,每条线程并行执行不同的任务。

1.2 并发与并行

  • 并发(Concurrency):指多个任务在同一时间段内交替执行。
  • 并行(Parallelism):指多个任务在同一时刻同时执行,通常需要多核处理器。

1.3 同步与互斥

  • 同步(Synchronization):协调多个线程的执行顺序,确保共享资源的安全访问。
  • 互斥(Mutex):确保同一时间只有一个线程可以访问共享资源。

2. 常用函数及其用法

-thread函数

2.1构造函数

用于创建一个新线程,并指定要执行的函数及其参数。

#include <iostream>
#include <thread>
using namespace std;
void func(int x, string str) {cout << "Thread running with x = " << x << " and str = " << str << endl;
}int main() {int a = 5;string s = "Hello";thread t(func, a, s); // 创建线程,执行func函数t.join(); // 等待线程完成,主线程会阻塞直到子线程结束。return 0;
}

 

detach() 函数

将线程分离,使其在后台运行,主线程不再等待子线程。

t.detach();//一旦线程被分离,就无法再与主线程同步

lock() 和unlock()

锁定互斥量,如果互斥量已被锁定,则阻塞直到解锁。

std::mutex mtx;
mtx.lock();
// 临界区
mtx.unlock();//解锁互斥量。

lock_guard用法

自动管理互斥量的生命周期,在构造时锁定互斥量,在析构时解锁。

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;void printThread(int id) {lock_guard<mutex> lock(mtx); // 自动锁定cout << "Thread " << id << " is running." << endl;// 自动解锁
}int main() {thread t1(printThread, 1);thread t2(printThread, 2);t1.join();t2.join();return 0;
}

unique_lock用法

提供更灵活的锁管理,可以手动锁定和解锁。

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;void func() {unique_lock<mutex> lock(mtx);// 执行操作lock.unlock(); // 手动解锁// 执行其他操作lock.lock(); // 重新锁定// 继续执行
}int main() {thread t(func);t.join();return 0;
}

 

 wait() 用法

使线程等待,直到被通知。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mtx;
condition_variable cv;
bool ready = false;void worker() {unique_lock<mutex> lock(mtx);cv.wait(lock, []{ return ready; }); // 等待通知cout << "Worker thread is running." << endl;
}int main() {thread t(worker);{lock_guard<std::mutex> lock(mtx);ready = true;}cv.notify_one(); // 唤醒一个等待的线程。同理也有notify_all唤醒所有等待的线程t.join();return 0;
}

atomic

提供原子操作,确保对变量的操作是原子的,避免数据竞争。

#include <iostream>
#include <thread>
#include <atomic>
using namespace std;
atomic<int> counter(0);void increment(int n) {for(int i = 0; i < n; ++i) {counter++;}
}int main() {thread t1(increment, 1000);thread t2(increment, 1000);t1.join();t2.join();cout << "Counter value: " << counter << endl;return 0;
}

3. 注意事项

3.1 避免数据竞争

确保对共享资源的访问是互斥的,使用互斥量或原子操作来防止数据竞争。

3.2 死锁预防

避免多个线程互相等待对方释放锁的情况。使用锁管理类如std::lock_guardstd::unique_lock可以帮助管理锁的生命周期。

3.3 线程安全

设计线程安全的类和方法,确保在多线程环境下正确处理共享资源。

3.4 性能考虑

过多的线程切换会带来性能开销,合理配置线程数量,避免过度创建线程。

3.5 异常处理

在线程函数中捕获并处理异常,避免未捕获的异常导致程序终止。

 

 

 

 

 

 

 

 

 

 

相关文章:

  • 记录一下学习kafka的使用以及思路
  • 黄金、碳排放期货市场API接口文档
  • AI日报 · 2025年5月09日|OpenAI Deep Research 上线 GitHub Connector Beta
  • 【相机标定】OpenCV 相机标定中的重投影误差与角点三维坐标计算详解
  • 【论文阅读】——Articulate AnyMesh: Open-Vocabulary 3D Articulated Objects Modeling
  • Python 基础语法与数据类型(六) - 条件语句、循环、循环控制
  • 全球实物文件粉碎服务市场洞察:合规驱动下的安全经济与绿色转型
  • Flink之Table API
  • U9C对接飞书审批流完整过程
  • 【软件测试】测试用例的设计方法
  • 深入理解 Istio 的工作原理 v1.26.0
  • 【LangChain高级系列】LangGraph第一课
  • 【强化学习】动态规划(Dynamic Programming, DP)算法
  • 从Dockerfile 构建docker镜像——保姆级教程
  • Docker容器启动失败?无法启动?
  • Day 15 训练
  • 基于springboot的海洋环保知识分享系统的设计与实现
  • 如何减少极狐GitLab 容器镜像库存储?
  • springboot ResetController RequestMapping 注解
  • VSCode如何解决打开html页面中文乱码的问题
  • 马上评丨全民定制公交,打开城市出行想象空间
  • 马云再次现身阿里打卡创业公寓“湖畔小屋”,鼓励员工坚持创业精神
  • 中国以优化营商环境为支点,为全球企业提供可预期市场环境
  • 中华人民共和国和俄罗斯联邦关于全球战略稳定的联合声明
  • 咖啡戏剧节举办第五年,上生新所“无店不咖啡,空间皆可戏”
  • 专访|李沁云:精神分析不会告诉你“应该怎么做”,但是……