DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

thread_group是boost库中的线程池类,内部使用的是boost::thread。

随着C++ 11标准的制定和各大编译器的新版本的推出(其实主要是VS2012的推出啦……),本着能用标准库就用标准库的指导原则,决定把项目中多线程相关的部分代码从boost::thread迁移到std::thread。

thread的迁移本身很简单,毕竟stl的很多功能是直接从boost发展而来的,基本上就是改一下头文件和名称空间的问题,例外是thread_group,thread_group是boost的组件,但并不是标准库的组件,所以需要自己实现一下。

说是自己实现,其实就是复制粘贴boost中的代码啦。但boost中的thread_group使用shared_mutex来进行线程同步,shared_mutex也没有进入标准库,所以需要用什么东西来替代一下。shared_mutex没能进入标准库的原因就是C++标准化委员会认为目前可行的shared_mutex实现方案在性能上并不合算,不如直接使用mutex,既然如此,就直接用mutex吧。相应的shared_lock也修改成lock_guard,完成。

复制代码
复制代码
#include <thread>
#include <mutex>
#include <list>
#include <memory>
namespace std { //兼容boost::thread_group //使用std::thread代替boost::thread,std::mutex代替boost::shared_mutex class thread_group { private: thread_group(thread_group const&); thread_group& operator=(thread_group const&); public: thread_group() {} ~thread_group() { for(auto it=threads.begin(),end=threads.end(); it!=end;++it) { delete *it; } } template<typename F> thread* create_thread(F threadfunc) { lock_guard<mutex> guard(m); auto_ptr<thread> new_thread(new thread(threadfunc)); threads.push_back(new_thread.get()); return new_thread.release(); } void add_thread(thread* thrd) { if(thrd) { lock_guard<mutex> guard(m); threads.push_back(thrd); } } void remove_thread(thread* thrd) { lock_guard<mutex> guard(m); auto it=std::find(threads.begin(),threads.end(),thrd); if(it!=threads.end()) { threads.erase(it); } } void join_all() { lock_guard<mutex> guard(m); for(auto it=threads.begin(),end=threads.end();it!=end;++it) { (*it)->join(); } } size_t size() const { lock_guard<mutex> guard(m); return threads.size(); } private: list<thread*> threads; mutable mutex m; }; }
复制代码
复制代码

——其实完全没意义嘛……

posted on   DoubleLi  阅读(7017)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2013-08-12 C++预编译头文件
2013-08-12 fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "stdafx.h
2013-08-12 hash与map的区别联系应用
2013-08-12 hash_map和map的区别
2013-08-12 STL中map与hash_map容器的选择收藏
2011-08-12 SVN安装配置与使用
点击右上角即可分享
微信分享提示