Added mutex for the loop count part to ensure corect data with threads.