Simplify the code a little, removing un-necessary mutex locks/unlocks. Provide slightly better diagnostic message in case of corruption. Use snprintf/strlcat instead of sprintf/strcat