Fix race conditions - acquire a lock before touching shared stuff