Lock the state change on exiting a thread.