Fix rare multithreading bug