Update Issue 40

Improve the clean up to avoid having the shutdown thread blocked