千家信息网

C++中为什么gsl::joining_thread好于std::thread

发表于:2025-12-03 作者:千家信息网编辑
千家信息网最后更新 2025年12月03日,本篇内容主要讲解"C++中为什么gsl::joining_thread好于std::thread",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"C++中为什
千家信息网最后更新 2025年12月03日C++中为什么gsl::joining_thread好于std::thread

本篇内容主要讲解"C++中为什么gsl::joining_thread好于std::thread",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"C++中为什么gsl::joining_thread好于std::thread"吧!

CP.25: gsl::joining_thread好于std::thread

Reason(原因)

joining_thread是一种在和作用域连结的线程。分离之后的线程很难监控。很难保证分离之后(或者存在潜在的分离可能性)的线程中不存在错误。

Example, bad(反面示例)

void f() { std::cout << "Hello "; }

struct F {
void operator()() const { std::cout << "parallel world "; }
};

int main()
{
std::thread t1{f}; // f() executes in separate thread
std::thread t2{F()}; // F()() executes in separate thread
} // spot the bugs
Example(示例)
void f() { std::cout << "Hello "; }

struct F {
void operator()() const { std::cout << "parallel world "; }
};

int main()
{
std::thread t1{f}; // f() executes in separate thread
std::thread t2{F()}; // F()() executes in separate thread

t1.join();
t2.join();
} // one bad bug left
Note(注意)

Make "immortal threads" globals, put them in an enclosing scope, or put them on the free store rather than detach(). Don't detach.

将"永远有效的线程"定义为全局的,将它们限制在一个封闭的作用域,或者将它们放在自由存储中而不是分离它们。不要分离线程。

Note(注意)

Because of old code and third party libraries using std::thread, this rule can be hard to introduce.

因为旧代码和第三方库在使用std::thread,本准则很难推广。

Enforcement(实施建议)

Flag uses of std::thread:

标记使用std::thread的代码:

  • Suggest use of gsl::joining_thread or C++20 std::jthread.

  • 建议使用gsl::joining_thread或者C++20引入的std::jthread.

  • Suggest "exporting ownership" to an enclosing scope if it detaches.

  • 如果需要分离线程,建议"输出所有权"到封闭的作用域。

  • Warn if it is not obvious whether a thread joins or detaches.

  • 如果不好判断线程会连结还是分离,报警。

到此,相信大家对"C++中为什么gsl::joining_thread好于std::thread"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

线程 C++ 作用 建议 代码 内容 示例 学习 实用 更深 有效 自由 不好 全局 兴趣 准则 原因 反面 可能性 实用性 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 宁波工程软件开发公司 云服务器端口映射本地电脑 自荐书大专计算机网络技术 软件开发生命周期模型特点 最大软件开发公司排名 魔兽怀旧服哪个服务器人多好玩 分销软件开发多少钱 网络安全可信吗 数据库范式设计 成都华宇科讯网络技术 服务器更新第三阶段 监控服务器是有哪些 甘肃省国家网络安全宣传 网络安全你知道吗公益短片 佛山自主可控软件开发代理价格 计算机网络技术数学真题 穿越火线与服务器连接失败 navicat数据库还原 婕斯租根服务器了吧 计算机网络设计和软件开发哪个好 描述数据库全体数据全局逻辑结构 软件开发需求设计是什么 数据库实例是什么 奔奔上货怎么清空数据库 各级政府和部门缺乏大型数据库 软件开发项目哪个比较好 任天堂大乱斗连接服务器出错 筛选后的粘贴数据库 金蝶软件数据库怎么查看 淘宝卖家应用软件开发
0