Added thread protection on debug and error functions