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

CPP多线程2:多线程竞争与死锁问题

在多线程编程中,多个线程协同工作能显著提升程序效率,但当它们需要共享和操作同一资源时,潜在的问题也随之而来;线程间的执行顺序不确定性可能导致资源竞争,可能引发死锁,让程序陷入停滞。

多线程竞争问题示例

我们现在已经知道如何在c++11中创建线程,那么如果多个线程需要操作同一个变量呢?

#include <iostream>
#include <thread>
using namespace std;
int n = 0;
void count10000() {for (int i = 1; i <= 10000; i++)n++;
}
int main() {thread th[100];for (thread &x : th)x = thread(count10000);for (thread &x : th)x.join();cout << n << endl;return 0;
}

可能的两次输出分别是:

991164
996417

我们的输出结果应该是1000000,可是为什么实际输出结果比1000000小呢?

在多线程的执行顺序——同时进行、无次序,所以这样就会导致一个问题:多个线程进行时,如果它们同时操作同一个变量,那么肯定会出错。为了应对这种情况,c++11中出现了std::atomic和std::mutex。

std::mutex

std::mutex是 C++11 中最基本的互斥量,一个线程将mutex锁住时,其它的线程就不能操作mutex,直到这个线程将mutex解锁。根据这个特性,我们可以修改一下上一个例子中的代码:

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;int n=0;
mutex mtx;
void count10000(){for(auto i=0;i<10000;i++){mtx.lock();n++;mtx.unlock();}
}
int main(){thread th[100];for (thread &x : th)x = thread(count10000);for (thread &x : th)x.join();cout<<n<<endl;return 0;
}

mutex的常用成员函数
在这里插入图片描述

std::lock_gard

使用mutex需要上锁解锁,但有时由于程序员忘记或者其他奇怪问题时,lock_gard可以自动解锁。其原理大概是构造时自动上锁,析构时自动解锁。示例如下:

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;int n=0;
mutex mtx;
void count100000(){for(auto i=0;i<100000;i++){lock_guard<mutex> lock1(mtx);n++;n--;}
}
int main(){thread th[10];for(int i=0;i<10;i++){th[i]=thread(count100000);}for(int i=0;i<10;i++){th[i].join();}cout<<n<<endl;return 0;
}

std::atomic

mutex很好地解决了多线程资源争抢的问题,但它也有缺点:太……慢……了……

比如前面我们定义了100个thread,每个thread要循环10000次,每次循环都要加锁、解锁,这样固然会浪费很多的时间,那么该怎么办呢?接下来就是atomic大展拳脚的时间了。

#include <iostream>
#include <atomic>
#include <thread>
using namespace std;atomic<int> n{0};// 列表初始化void count10000(){for(int i=0;i<10000;i++)n++;
}int main(){thread th[10];for(thread& x:th)x=thread(count10000);for(auto& x:th)x.join();cout<<n<<endl;return 0;
}

可以看到,我们只是改动了n的类型(int->std::atomic_int),其他的地方一点没动,输出却正常了。

atomic,本意为原子,可解释为:

原子操作是最小的且不可并行化的操作。

atomic常用成员函数
在这里插入图片描述

死锁问题

在多个线程中由于上锁顺序问题可能导致线程卡死,如下:

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;int n=0;
mutex mtx1;
mutex mtx2;
void count100000(){for(auto i=0;i<100000;i++){lock_guard<mutex> lock1(mtx1);lock_guard<mutex> lock2(mtx2);n++;n--;}
}
void count200000(){for(auto i=0;i<200000;i++){lock_guard<mutex> lock2(mtx2);lock_guard<mutex> lock1(mtx1);n++;n--;}
}
int main(){thread th[10];for(int i=0;i<10;i++){if(i%2==0)th[i]=thread(count100000);elseth[i]=thread(count200000);}for(int i=0;i<10;i++){th[i].join();}cout<<n<<endl;return 0;
}

这是因为在一个线程count100000中mtx1上锁后,另一个线程count200000也正好将mtx2上锁,于是这两个线程没办法获得另一个mutex,这就是死锁问题。

解决方法就是保持一样的上锁顺序,于是当一个线程A抢到第一个mutex时,其他线程无法再获得mutex,即只能线程A按着顺序处理完所有事物。示例如下:

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;int n=0;
mutex mtx1;
mutex mtx2;
void count100000(){for(auto i=0;i<100000;i++){lock_guard<mutex> lock1(mtx1);lock_guard<mutex> lock2(mtx2);n++;n--;}
}
void count200000(){for(auto i=0;i<200000;i++){lock_guard<mutex> lock1(mtx1);lock_guard<mutex> lock2(mtx2);n++;n--;}
}
int main(){thread th[10];for(int i=0;i<10;i++){if(i%2==0)th[i]=thread(count100000);elseth[i]=thread(count200000);}for(int i=0;i<10;i++){th[i].join();}cout<<n<<endl;return 0;
}
http://www.lryc.cn/news/623158.html

相关文章:

  • RK3568 NPU RKNN(三):RKNN-ToolKit2模型构建与推理
  • 微服务架构实战指南:从单体应用到云原生的蜕变之路
  • AUTOSAR进阶图解==>AUTOSAR_SWS_FlexRayTransceiverDriver
  • 如何在FastAPI中玩转APScheduler,实现动态定时任务的魔法?
  • 【Docker】Ubuntu上安装Docker(网络版)
  • 储能领域大数据平台的设计中如何使用 Hadoop、Spark、Flink 等组件实现数据采集、清洗、存储及实时 / 离线计算,支持储能系统分析与预测
  • 打卡day40
  • 一些 DS 题目
  • Spark 数据分发性能深度剖析:mapPartitions vs. UDF – 你该选择哪一个?
  • docker-compose-mysql-定时备份数据库到其他服务器脚本
  • 【Web后端】Django、flask及其场景——以构建系统原型为例
  • 【OpenGL】LearnOpenGL学习笔记09 - 材质、光照贴图
  • 体彩排列三第2025218期号码分析
  • [Python]PTA:for 求奇数分之一序列前N项和
  • OpenWrt的快速设置向导功能与相关问题解答
  • Media Controller API 介绍
  • ClickHouse的学习与了解
  • 离线环境中使用ISO文件构建Yum源
  • 双重调度(Double Dispatch):《More Effective C++》条款31
  • 视频理解综述
  • 低空经济产业链全景解析
  • cPanel Python 应用部署流程
  • 存算分离与云原生:数据平台的新基石
  • Flowith-节点式GPT-4 驱动的AI生产力工具
  • 数据结构初阶(17)排序算法——非比较排序(计数排序·动图演示)、排序算法总结
  • 基于Spring Boot的快递物流仓库管理系统 商品库存管理系统
  • 中国大学排名爬取与数据分析案例总结
  • 深入解析 @nestjs/typeorm的 forRoot 与 forFeature
  • UDP/TCP套接字编程简单实战指南
  • 【深度学习】基于ESRNet模型的图像超分辨率训练