Fix some race conditions