Fixed racing conditions by adding a lock.