Add locks to fix various race conditions