如何知道线程/进程何时完成

时间:2020-09-28 15:32:22

标签: python multithreading multiprocessing

感谢您阅读。

调用一个函数(get_connection)时,我将获得当前线程/进程的连接,如果不存在,则将创建它。

我怎么知道线程/进程何时完成,以便释放这些连接?
谁将调用函数_on_thread_process_terminate。畅通无阻?
如果我喜欢捕获线程和进程,则需要使用什么锁。是threading.Lock还是multiprocessing.Lock?

有办法知道吗?

例如:

class MyClass(object):
    def __init__(self):
        self._pid_to_resource = {}
        self._lock = Lock()

    def _on_thread_process_terminate(self, pid):
        self._lock.acquire()
        try:
            self._pid_to_resource[pid].disconnect()
            del self._pid_to_resource[pid]
        finally:
            self._lock.release()
        
    def get_connection(self):
        self._lock.acquire()
        try:
            pid = threading.get_native_id()
            if pid in self._pid_to_resource:
                conenction = self._pid_to_resource.get(pid)
            else:
                conenction = connect_to_x()
                self._pid_to_resource[pid] = conenction
                
                # HOW TO LISTEN TO THREAD/PROCESS FINISHED EVENT
                # How to wait to pid in a nonblocking way?
                # wait_for_pid(pid, self._on_thread_process_terminate)
            return conenction
        finally:
            self._lock.release()


非常感谢您。
最好的谢伊

0 个答案:

没有答案