Improve thread handling