tweak to make more multiprocess-friendly
fix deadlock when run using multiprocessing