Revert "Revert "change locking to a mutex""

Revert a fail revert

This reverts commit 45f551b1fbc80cbe447004d2b019fcec885e8deb.