Quantcast
Channel: User Peter - Reinstate Monica - Stack Overflow
Viewing all articles
Browse latest Browse all 223

std::async: does "as if in a new thread" guarantee that it is safe to use mutexes?

$
0
0

The 2020 standard says (23.9.9/4.1):

If launch::async is set in policy, calls invoke(decay-copy(std::forward(f)), decaycopy(std::forward(args))...) (20.14.4, 32.4.3.3) as if in a new thread of execution [...].

Does "as if" in a new thread guarantee that I can use std::mutex to protect resources accessed by multiple parallel thingies started with async? It works very well, but that means nothing when it comes to concurrency, does it.

Even though this seems the intent and many tutorials do that, I'm asking because ordinary mutexes absolutely must not be locked twice from the same thread. And because mutexes and threads may map 1:1 to system resources, some magic must be done if two async thingies may interleave on the same system thread and lock the same mutex.1

Tangentially related was a similar issue with thread_local variables in async thingies that were re-using threads from a thread pool. Apparently, the consensus was formed that "as if" here implies "as-if-thread local", i.e., the behavior should indeed completely mimic running on different threads. (Re-using a thread linearly for a next async thingie after some predecessor has finished should not be an issue for mutexes anyway because a thread and presumably also a thingie must not end while still locking a mutex, i.e., all mutexes are unlocked by the time the new thingie starts.)

Presumably, "as if" in a new thread is the case for mutexes as well.

Is it?


1 An example for such interleaving were Java's Green threads which all mapped to the same OS thread.


Viewing all articles
Browse latest Browse all 223

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>