Fixed (I think) the threading issues

The problem is deep, and although I'm not sure I have eliminated the possibility of a race condition, I am hopeful this should be largely successful.