Changed from mutex to atomic_flag for efficiency