Exit properly from thread