Fix memory leak on thread/process exit