C++多线程Demo

《C++多线程Demo》

  多线程访问共享资源时,采取对资源加锁的方式来防止产生脏数据和错误。多线程访问同一个数据库时,数据库是共享资源,所以对库操作要加锁。对于操作同一个数据结构对象的时候也是一样的。

Key Words:C++多线程、map接收线程结果


Beijing, 2020

作者:RaySue

Agile Pioneer  

定义线程函数

  用map接受线程返回数据, 这里介绍一种场景比较简单的多线程结果汇总的用法,使用map对多线程的结果进行收集,在线程读写的map的时候加锁。

#include<mutex>

std::mutex mtx;

void threadClsTask(int begin, int end, vector<Mat> imgList, BSMobileNet *bsMobileNet, map<int, int> *bsInfo){
    int clsRes = bsMobileNet->inference(imgList[begin]);
    mtx.lock();
    bsInfo->insert(pair<int, int>(begin, clsRes));
    mtx.unlock();
}

void threadWEBSTask(int begin, int end, vector<Mat> imgList, WEBSAlg *wsICNet, map<int, WE_BS_Res> *wsInfo){
    WE_BS_Res weBsRes;
    wsICNet->inference(imgList[begin], weBsRes);
    mtx.lock();
    wsInfo->insert(pair<int, WE_BS_Res>(begin, weBsRes));
    mtx.unlock();
}

多线程调用

int algThreadNum = 6;
std::thread threads[algThreadNum];
map<int, int> *bsInfo = new map<int, int>();
map<int, float> *wsInfo = new map<int, float>();

threads[0] = thread(threadClsTask, 0, 0, imgList, &bsMobileNet1, bsInfo);
threads[1] = thread(threadSegTask, 0, 0, imgList, &wsICNet1, wsInfo);

threads[2] = thread(threadClsTask, 1, 1, imgList, &bsMobileNet2, bsInfo);
threads[3] = thread(threadSegTask, 1, 1, imgList, &wsICNet2, wsInfo);

threads[4] = thread(threadClsTask, 2, 2, imgList, &bsMobileNet3, bsInfo);
threads[5] = thread(threadSegTask, 2, 2, imgList, &wsICNet3, wsInfo);

for (auto &t : threads){
	t.join();
}

delete bsInfo;
delete wsInfo;

  多线程的互斥情况在代码编写过程中是经常遇到的。所以,每次对共享数据进行操作时,都需要对数据进行 EnterCriticalSection 和 LeaveCriticalSection 的操作。但是,这中间也不是一帆风顺的。很有可能你会遇到各种各样的错误。那么,这时候你的程序就需要跳出去了。可能一开始遇到 error 的时候,你还记得需要退出临界区。但是,如果错误多了,你未必记得还有这个操作了。这一错就完了,别的线程就没有机会获取这个锁了。

  C++ 的一个重要特点就是,不管函数什么时候退出,系统都会自动调用类的析构函数。在Process类的data_process函数中,函数在开始就创建了一个CLock类。那么,在创建这个类的时候,其实就开始了临界区的pk。那么一旦进入到临界区当中,在error中能不能及时退出临界区呢?此时,c++析构函数的优势出现了。因为不管错误什么时候出现,在函数退出之前,系统都会帮我们善后。什么善后呢?就是系统会调用CLock的析构函数,也就是退出临界区。这样,我们的目的就达到了。

《c++并发编程实战》
c++实现线程安全的map
https://blog.youkuaiyun.com/eulb/article/details/2177500
https://blog.youkuaiyun.com/zkkdcs1/article/details/89400259

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值