std::list<std::future> destructor does not block

只愿长相守 提交于 2019-12-05 00:47:34

This is a MSVC bug that has been fixed, but the fix won't be available until MS releases a new version of Visual C++, probably some time in 2015. (It's also available in the CTP for the new version, but it's a pretty bad idea to use that for any production code...)

As Scott Meyers explained in his blog post, the destructor of a std::future returned by a std::async call using the launch::async policy is required to block until the spawned thread completes execution (§30.6.8 [futures.async]/p5):

If the implementation chooses the launch::async policy,

  • [...]
  • the associated thread completion synchronizes with (1.10) the return from the first function that successfully detects the ready status of the shared state or with the return from the last function that releases the shared state, whichever happens first.

In this case, the future's destructor is the "last function that releases the shared state", so the thread completion must synchronize with (i.e., happen before) the return of that function.

I've looked at the documentation of std::future and found this for the destructor of std::future:

Releases any shared state. This means

  • if the return object or provider holds the last reference to its shared state, the shared state is destroyed; and
  • the return object or provider gives up its reference to its shared state; and
  • these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state.

Pay attention on the last point. In my opinion you have to call the get's at the end of your scope.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!