fix a race condition between the death of a thread that communicates with an UI event loop and the event loop itself.

The comment tries to explain it all. There may be a better solution, but I believe that this one is
(a) safe (b) better than the old approach.