Thread safety improvements (using mutex) and some architectural improvements