Two commits, two fixes.
First is an obscure infinite loop on Windows (and possible crash-at-shutdown). Most of the difference in that commit are just an indentation change from switching from LOCK(cs_...) to using mutexDebugLock.
Second is a fix for an obscure crash-at-shutdown on all platforms.
Tested by running without -debug, with -debug and with -debug=net -debug=mempool.