Safe cancelling of threads