Search code examples
c++multithreadingc++11std-function

std::function concurrency with assignment operator and call operator


Can std::function::operator= and std::function::operator() be called concurrently?

Is it undefined behavior to do a std::function::operator= on thread one while doing a std::function::operator() on thread two.

I assume this might be an atomic operation and we can't be halfway between which function gets invoked. I'm not concern about which one runs only that we are not in some invalid state.


Solution

  • "[res.on.objects]/1 The behavior of a program is undefined if calls to standard library functions from different threads may introduce a data race. The conditions under which this may occur are specified in 20.5.5.9. [ Note: Modifying an object of a standard library type that is shared between threads risks undefined behavior unless objects of that type are explicitly specified as being sharable without data races or the user supplies a locking mechanism. —end note ]" –

    Comment by: Igor Tandetnik

    That being said I found a workaround to do what I wanted. It's possible to do an assignment in the call operator. This means I don't need to do the assignment on a different thread.