Add threading lock to prevent race conditions