代码之家  ›  专栏  ›  技术社区  ›  HaiFengZeng

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

  •  2
  • HaiFengZeng  · 技术社区  · 8 年前

    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 穿线。线 查找线程 .

    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
    

    有可能做到这一点吗?如何做到?

    1 回复  |  直到 8 年前
        1
  •  2
  •   GIZ    8 年前

    你的代码看起来一切都很好,你只需要稍微修改一下。你已经使用了 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 是线程处理所需的。