如何将参数传递到运行的Python线程



我有一个从 threading.Thread延长的类A,现在我想将参数传递到运行的线程中,我可以通过以下脚本获得我想要的线程:

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_threadthreading.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进行处理。

最新更新