Fix problems when running with multiple threads