Fix thread race conditions

I ran into a couple of race conditions that I've tried to address in this pull request.

The first commit in this pull request is a command line tool that exposes the bugs. The following two commits are my attempts at fixing the race conditions. See respective commits for details.