Fixed a potential deadlock and made some minor fixes.

``+=`` opereation is not atomic and so I lock was needed.