Fix race condition and sync script threads