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

2020-07-14 16:20:17 浏览数 (1)

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

0 人点赞