Various fixes for thread safety