From 68700d4c3ad4d5716585765a04c51f4d1f4506a0 Mon Sep 17 00:00:00 2001 From: Alexander Grund Date: Thu, 10 Feb 2022 11:42:33 +0100 Subject: [PATCH] Document mechanism used in the functor constructor --- include/turtle/detail/functor.hpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/include/turtle/detail/functor.hpp b/include/turtle/detail/functor.hpp index e4ce1e8..dfb793d 100644 --- a/include/turtle/detail/functor.hpp +++ b/include/turtle/detail/functor.hpp @@ -27,16 +27,25 @@ namespace mock { namespace detail { functor() { scoped_lock _(functor_mutex); - static functor* f = 0; + // MOCK_FUNCTOR creates 2 functor objects: + // The user-usable one with the passed name and a 2nd used by MOCK_EXPECT with a suffixed name + // We need the 2nd to be a copy of the first and use a static variable for storing a pointer to the first + static functor* f = nullptr; if(f) { - *this = *f; - f = 0; + // Release the lock from the first call (see below) so other threads can create functors again + // after the function exits (the scoped_lock still holds the mutex) functor_mutex.unlock(); + // Copy the first functor to the current (2nd) one + *this = *f; + f = nullptr; } else { - functor_mutex.lock(); + // This is the first object, store its pointer f = this; + // Lock the mutex again so only this thread can create new instances of a functor + // making sure that we copy the right instance above and not one from a concurrent thread + functor_mutex.lock(); } } };