python线程可以将状态发送回主线程吗

python线程可以将状态发送回主线程吗,python,multithreading,Python,Multithreading,我有一个Python3程序,它创建了一系列10个线程,它们自己做各种工作。有没有办法让这些线程将状态发送回主线程 我知道我可以从main调用is_alive()并得到一个“hearbeat”,但我要寻找的不仅仅是布尔值。有没有一种方法可以让我在任何给定时间从线程中收集一系列值?是的,有很多方法可以做到这一点。一个是由保护的简单共享变量。为此,您可以执行以下操作: def function_called_in_thread(shared_variable, shared_lock): # d

我有一个Python3程序,它创建了一系列10个线程,它们自己做各种工作。有没有办法让这些线程将状态发送回主线程


我知道我可以从main调用
is_alive()
并得到一个“hearbeat”,但我要寻找的不仅仅是布尔值。有没有一种方法可以让我在任何给定时间从线程中收集一系列值?

是的,有很多方法可以做到这一点。一个是由保护的简单共享变量。为此,您可以执行以下操作:

def function_called_in_thread(shared_variable, shared_lock):
   # do stuff
   with shared_lock:
       # e.g. if it's an integer and it's a heartbeat count
       shared_variable += 1
       # e.g. if it's a list
       shared_variable.append(some_result)
# assuming it's an integer
shared_variable = 0
lock = threading.Lock()
thread = Thread(target=function_called_in_thread, args=(shared_variable, lock))
thread.start()
# A loop to check on the status of the thread via the shared variable
while True:
    with lock:
      print('The value of the shared variable is:', shared_variable)
    time.sleep(10)
然后在主线程中执行以下操作:

def function_called_in_thread(shared_variable, shared_lock):
   # do stuff
   with shared_lock:
       # e.g. if it's an integer and it's a heartbeat count
       shared_variable += 1
       # e.g. if it's a list
       shared_variable.append(some_result)
# assuming it's an integer
shared_variable = 0
lock = threading.Lock()
thread = Thread(target=function_called_in_thread, args=(shared_variable, lock))
thread.start()
# A loop to check on the status of the thread via the shared variable
while True:
    with lock:
      print('The value of the shared variable is:', shared_variable)
    time.sleep(10)

还有一些专门构建的数据结构,用于在线程之间共享信息,包括。其他对象,例如,和,让线程协调,以便它们可以等待,直到另一个线程达到某个目标。

回答得很好。讽刺的是,我没有用你的密码。但是你提到了队列对象,这正是我想要反复讨论的。谢谢