前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >C++核心准则CP.61:使用async启动并发任务

C++核心准则CP.61:使用async启动并发任务

作者头像
面向对象思考
发布2020-07-16 17:28:52
发布2020-07-16 17:28:52
61800
代码可运行
举报
运行总次数:0
代码可运行

CP.61: Use async() to spawn concurrent tasks

CP.61:使用async启动并发任务

Reason(原因)

Similar to R.12, which tells you to avoid raw owning pointers, you should also avoid raw threads and raw promises where possible. Use a factory function such as std::async, which handles spawning or reusing a thread without exposing raw threads to your own code.

R.12告诉我们避免原始的所有权指针,本规则告诉我们:如果可能应该避免原始线程和promise。使用像std::async一样的工厂函数,它可以可以启动和重新使用线程而不必向外部代码保护原始线程。

Example(示例)

代码语言:javascript
代码运行次数:0
复制
int read_value(const std::string& filename)
{
    std::ifstream in(filename);
    in.exceptions(std::ifstream::failbit);
    int value;
    in >> value;
    return value;
}

void async_example()
{
    try {
        std::future<int> f1 = std::async(read_value, "v1.txt");
        std::future<int> f2 = std::async(read_value, "v2.txt");
        std::cout << f1.get() + f2.get() << '\n';
    } catch (const std::ios_base::failure& fail) {
        // handle exception here
    }
}
Note(注意)

Unfortunately, std::async is not perfect. For example, it doesn't use a thread pool, which means that it may fail due to resource exhaustion, rather than queuing up your tasks to be executed later. However, even if you cannot use std::async, you should prefer to write your own future-returning factory function, rather than using raw promises.

不幸的是,std::async并不完美。例如,它没有使用线程池,这意味着它可能因为资源枯竭而失败,而不是将任务排队等候执行。然而,即使你不能使用std::async,你还是可以编写自己的返回future的工厂函数,而不是使用原始的promise。

Example (bad)(反面示例)

This example shows two different ways to succeed at using std::future, but to fail at avoiding raw std::thread management.

示例代码演示了两种不同的成功使用std::future的方式,但是没能避免使用原始的std::thread。

代码语言:javascript
代码运行次数:0
复制
void async_example()
{
    std::promise<int> p1;
    std::future<int> f1 = p1.get_future();
    std::thread t1([p1 = std::move(p1)]() mutable {
        p1.set_value(read_value("v1.txt"));
    });
    t1.detach(); // evil

    std::packaged_task<int()> pt2(read_value, "v2.txt");
    std::future<int> f2 = pt2.get_future();
    std::thread(std::move(pt2)).detach();

    std::cout << f1.get() + f2.get() << '\n';
}
Example (good)(范例)

This example shows one way you could follow the general pattern set by std::async, in a context where std::async itself was unacceptable for use in production.

示例代码显示了你可以遵守的,由std::async设定的通常模式,这种模式可以用于开发过程中std::async无法直接使用的情况。

代码语言:javascript
代码运行次数:0
复制
void async_example(WorkQueue& wq)
{
    std::future<int> f1 = wq.enqueue([]() {
        return read_value("v1.txt");
    });
    std::future<int> f2 = wq.enqueue([]() {
        return read_value("v2.txt");
    });
    std::cout << f1.get() + f2.get() << '\n';
}

Any threads spawned to execute the code of read_value are hidden behind the call to WorkQueue::enqueue. The user code deals only with future objects, never with raw thread, promise, or packaged_task objects.

任何启动并调用read_value的线程都被隐藏在WorkQueue::enqueue的调用后面。用户代码智能处理future对象,永远不会使用原始线程,promise或者打包的task对象。

Enforcement(实施建议)

???

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp61-use-async-to-spawn-concurrent-tasks

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • CP.61: Use async() to spawn concurrent tasks
  • Reason(原因)
    • Note(注意)
    • Example (bad)(反面示例)
    • Example (good)(范例)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档