fixed bugs in thread management