threads: fix leaks on error path