Fixed race conditions in thread tests; exposed by UBSan