Skip to main content
 首页 » 编程设计

python之如何将参数传递给正在运行的 python 线程

2025年02月15日9artech

我有一个类A扩展自threading.Thread,现在我想将参数传递给正在运行的线程,我可以通过以下方式获得我想要的线程脚本:

find_thread = None 
for thread in enumerate(): 
    if thread.isAlive(): 
        name = thread.name.split(',')[-1] 
        if name == player_id: 
            find_thread = thread #inject the parameter into this thread 
            break 

find_thread 是 threading.Thread 的一个实例,我在 find_thread 中有一个队列。

class A(threading.Thread): 
    def __init__(self,queue): 
        threading.Thread.__init__(self) 
        self.queue =queue 
    def run(): 
        if not self.queue.empty(): #when it's running,I want to pass the parameters here 
            a=queue.get() 
            process(a) #do something 

是否可以这样做以及如何做到?

请您参考如下方法:

您的代码似乎一切正常,您只需稍微修改一下即可。您已经使用过 threading.Queue 我相信,您还使用了队列的 get 方法所以我想知道为什么您不能使用它的 put方法:

for thread in enumerate(): 
    if thread.isAlive(): 
        name = thread.name.split(',')[-1] 
        if name == player_id: 
            find_thread = thread 
            find_thread.queue.put(...)  # put something here 
            break 

class A(threading.Thread): 
    def __init__(self,queue): 
        threading.Thread.__init__(self, queue) 
        self.queue = queue 
    def run(): 
        a = queue.get()                 # blocks when empty 
        process(a) 
 
queue = Queue() 
thread1 = A(queue=queue,...) 

我删除了对空队列的检查,当队列为空时 queue.get 阻塞,使得这里的检查变得无意义,这是因为你的线程需要 a进行处理。