简体   繁体   English

从multiprocessing.Process内部调用线程时,is_alive()始终返回False。

[英]is_alive() always returns False when called on a Thread from inside multiprocessing.Process

I'm trying to use a thread inside a process, I would also like to check if the thread is still running from within the process. 我正在尝试在进程内使用线程,我还想检查线程是否仍在进程内运行。 The problem I'm facing is that when I run the same code inside a process is_alive() called on the thread always returns False . 我面临的问题是,当我在线程上调用的进程is_alive()内运行相同的代码时,始终返回False

from threading import Thread
from multiprocessing import Process
import time

class WorkerThread(Thread):
    def run(self):
        i = 0 
        while i < 10:
            print ("worker running..")
            time.sleep(1)
            i += 1

class ProcessClass:
    def run_worker(self, worker):
        self.worker = worker
        self.worker.daemon = True
        self.worker.start()
        i = 0
        while i < 12:
            print (F"Is worker thread alive? {self.worker.is_alive()}")
            time.sleep(1)
            i += 1

worker = WorkerThread()
processclass = ProcessClass()

# Calling directly works as expected
processclass.run_worker(worker)

When I call the method directly is_alive() works as expected, but when calling the method inside a process, it always returns False 当我直接调用该方法时, is_alive()可以正常工作,但是在进程内部调用该方法时,它总是返回False

# Calling inside a process always returns False
parentProcess = Process(target = processclass.run_worker, args = (worker,))
parentProcess.start()

You should pass the thread class, not an instance, and have run_worker create the instance. 您应该传递线程类而不是实例,并让run_worker创建该实例。

class ProcessClass:
    def run_worker(self, worker):
        self.worker = worker()
        ...

worker = WorkerThread

This way the thread is created in the child process rather than in the parent with a reference passed to the child. 这样,线程将在子进程中创建,而不是在父进程中通过传递给子进程的引用创建。

Process es are separate processes ; Process是独立的流程 ; threads are local to a single process. 线程是单个进程本地的。 Even when you fork (the default mechanism behind Process on UNIX-like systems), only the thread that fork ed continues to exist in the new process, no other thread survives the fork (this is why mixing threads and fork is dangerous; if one of those other threads holds a lock at the time of the fork , that lock remains held by a non-existent thread in the child). 甚至当你fork (后面的默认机制Process的类UNIX系统),只有线程fork版继续在新的进程存在,没有其它线程生存的fork (这就是为什么混合线程和fork是危险的;如果一个这些其他线程中的一个在fork时持有一个锁,该锁仍由子代中不存在的线程持有。

If you want the thread to run in the child, create it there (within the function passed as the target to Process ), not in the parent process. 如果希望线程在子进程中运行,请在子进程中创建它(在作为target传递给Process的函数内),而不是在父进程中创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM