Better handling of thread on exit