如何将参数传递给 运行 python 线程
How to pass parameters to a running python thread
我有一个class 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
进行处理。
我有一个class 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
进行处理。