Adding a mutual exclusion for thread safety. This fixes a bug that produced a number of error reports upon shutdown.