fix valgrind warnings

* there were some write-read race conditions that shouldn't have caused
  much damage, but if helgrind complains, I invoke compiler specific
  __sync_fetch_and_* builtins. That gets rid of the complaints.