Lock around read and write routines to avoid race conditions; seems to work