c++threadpoolstdasync

Can a task executed by C++ std::async(std::launch::async...) be switched/stolen between threads?


In C++ on Windows, given a task started by std::async(std::launch::async, ...), can it be executed first by one thread, and after a possible context switch, stolen and executed by another thread?

For example, if inside of my task I create some thread_local variables, will they be preserved?

This doubt was motivated by a comment of my coworker, who read this paragraph


Solution

  • No.

    Context switches move threads between cores. C++ thread_local objects move with the thread.

    You do not know which thread will be used for std::async, or which thread_local objects already exist in that thread. That's abstracted away. (And one of the reasons I think std::async is not very useful - it has no concrete, reliable benefits but does have concrete limitations. It's similar to std::stack in that sense.)