Exit and join all threads, before destroying any mutexes in the main thread
Otherwise, the mutex could be locked by another thread, and destroying a locked mutex triggers undefined behaviour.
Part of legacy/trac#31614 (moved).
Updated to add:
Instead of exiting and joining threads, we can initialize the mutex once, and never destroy it. If we use a sentinel value, like log_mutex_initialized, then we won't re-initialize the mutex when we re-initialize everything else.