Fixed a bug in thread closing