Thread safety

but not related to the original PR. I suggest you gather up any other unrelated changes and apply them in your own PR later, or if the changes are small just commit them directly in master :)