Added mutexes to ensure safe multi-threading.