WIP: Make unit tests ThreadSanitizer clean
This MR fixes the unit tests and associated library files to be ThreadSanitizer clean. This often involved adding locking around variables possibly shared among threads or converting global variables to atomic.
Closes #1119 (closed), #1180 (closed)
Edited by Ondřej Surý