5

Using the standard development tools and compilers for the platform[1], does std::async spawn a new OS thread for each background job or does it use a thread pool or some system based on work stealing task queues?

  1. Xcode, Clang/LLVM
ahcox
  • 9,349
  • 5
  • 33
  • 38

2 Answers2

5

An application built with the standard toolchain for the platform (Xcode/Clang) does not use a thread pool. The base of the stack of a task launched with std::async contains std::thread and pthread calls.

Stack trace showing async job running on a dedicated OS thread

On exit, each job calls pthread_exit() to kill the thread running it.

enter image description here

Xcode 8.3.3 also uses an OS thread per job launched with std::async when building for iOS (Tested on original iPad Pro 9.7" target).

enter image description here

ahcox
  • 9,349
  • 5
  • 33
  • 38
1

No major standard implementation currently uses thread pools for std::async. Despite that notion that implementation could do this, this would be extremely hard in practice for implementations, and I do not foresee it in any near future.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Did the Visual Studio one back off from doing this? – ahcox Aug 04 '17 at 15:55
  • MSVC one certainly seems to be reusing threads from a thread pool. Check this very nice answer [here](https://stackoverflow.com/questions/15666443/which-stdasync-implementations-use-thread-pools) – TheWaterProgrammer Aug 04 '17 at 16:50
  • 1
    @Programist, just plain read of documentation doesn't [support](https://learn.microsoft.com/en-us/cpp/standard-library/future-functions) this statement: `If policy is launch::async, the function **creates a thread** that evaluates INVOKE(dfn, dargs..., Ty). The function returns after it creates the thread without waiting for results. If the system can't **start a new thread**, the function throws a system_error that has an error code of resource_unavailable_try_again.` – SergeyA Aug 04 '17 at 16:57
  • @ahcox, their documentation certainly indicates this. – SergeyA Aug 04 '17 at 17:00
  • ok. my understanding was wrong then. it spawns a new single thread for each background task. – TheWaterProgrammer Aug 05 '17 at 07:06
  • to add a little more, it is very similar to what Android's [AsyncTask](https://developer.android.com/reference/android/os/AsyncTask.html) does in java. – TheWaterProgrammer Aug 05 '17 at 07:10
  • @Programist, last time I checked the Android source code (~2010) AsyncTask was using a thread pool. – ahcox Aug 07 '17 at 12:37