前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则CP.41:尽量回避线程的生成和销毁处理

C++核心准则CP.41:尽量回避线程的生成和销毁处理

作者头像
面向对象思考
发布2020-07-14 16:20:17
3280
发布2020-07-14 16:20:17
举报

CP.41: Minimize thread creation and destruction

CP.41:尽量回避线程的生成和销毁处理

Reason(原因)

Thread creation is expensive.

创建线程代价高昂。

Example(示例)

代码语言:javascript
复制
void worker(Message m)
{
    // process
}

void dispatcher(istream& is)
{
    for (Message m; is >> m; )
        run_list.push_back(new thread(worker, m));
}

This spawns a thread per message, and the run_list is presumably managed to destroy those tasks once they are finished.

Instead, we could have a set of pre-created worker threads processing the messages

代码中为每个消息生成一个线程,而且run_list很可能准备在任务结束时销毁它们。

作为改善,我们可以准备一组事先生成的工作线程来处理这些消息。

代码语言:javascript
复制
Sync_queue<Message> work;

void dispatcher(istream& is)
{
    for (Message m; is >> m; )
        work.put(m);
}

void worker()
{
    for (Message m; m = work.get(); ) {
        // process
    }
}

void workers()  // set up worker threads (specifically 4 worker threads)
{
    joining_thread w1 {worker};
    joining_thread w2 {worker};
    joining_thread w3 {worker};
    joining_thread w4 {worker};
}
Note(注意)

If your system has a good thread pool, use it. If your system has a good message queue, use it.

如果你的系统包含一个优秀的线程池,使用它。如果你的系统包含一个优秀的消息队列,使用它。

Enforcement(实施建议)

???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp41-minimize-thread-creation-and-destruction

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • CP.41: Minimize thread creation and destruction
  • Reason(原因)
    • Note(注意)
    相关产品与服务
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档