Fix thread synchronization bug