Replace mutex implementation, and fix a few bugs.