Improved locking, fixing a more or less theoretical bug.