std :: async函数串行运行 [英] std::async function running serially

查看:127
本文介绍了std :: async函数串行运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在for循环中将std :: async与launch :: async一起使用时,我的代码在同一线程中串行运行,就像每个异步调用在启动之前都等待前一个一样.在std :: async引用的注释中( std: :async ),如果std :: future未绑定到引用,则可能发生这种情况,但我的代码并非如此.谁能弄清楚为什么它串行运行?

When using std::async with launch::async in a for loop, my code runs serially in the same thread, as if each async call waits for the previous before launching. In the notes for std::async references (std::async), this is possible if the std::future is not bound to a reference, but that's not the case with my code. Can anyone figure out why it's running serially?

这是我的代码段:

class __DownloadItem__ { //DownloadItem is just a "typedef shared_ptr<__DownloadItem__> DownloadItem"
    std::string buffer;
    time_t last_access;
 std::shared_future<std::string> future;
}

for(uint64_t start: chunksToDownload){
        DownloadItem cache = std::make_shared<__DownloadItem__>();
        cache->last_access = time(NULL);
        cache->future =
                std::async(std::launch::async, &FileIO::download, this, api,cache, cacheName, start, start + BLOCK_DOWNLOAD_SIZE - 1);
     }
}

将来存储在共享的将来中,因为多个线程可能正在等待相同的将来.

The future is being stored in a shared future because multiple threads might be waiting on the same future.

我也在使用GCC 6.2.1进行编译.

I'm also using GCC 6.2.1 to compile it.

推荐答案

在析构函数中,async返回的std::future块.也就是说,当您到达

The std::future returned by async blocks in the destructor. That means when you reach the } of

for(uint64_t start: chunksToDownload){
    DownloadItem cache = std::make_shared<__DownloadItem__>();
    cache->last_access = time(NULL);
    cache->future =
            std::async(std::launch::async, &FileIO::download, this, api,cache, cacheName, start, start + BLOCK_DOWNLOAD_SIZE - 1);
 }  // <-- When we get here

cache被销毁,进而调用future的析构函数,该析构函数等待线程完成.

cache is destroyed which in turn calls the destructor offuture which waits for the thread to finish.

您需要做的是将从async返回的每个future存储在单独的持久化future中,该持久性在for循环之外声明.

What you need to do is store each future returned from async in a separate persistent future that is declared outside of the for loop.

这篇关于std :: async函数串行运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆