adding locking when terminating