Fixed race condition in shutdown

Fixes #29