您可以使用
multiprocessing
为此:
import time
import multiprocessing
def exchange1(q):
while True:
time.sleep(2)
q.put([1, 2, 3, 4, 5])
def exchange2(q):
while True:
time.sleep(4)
q.put([4, 5, 6, 7, 8])
if __name__ == "__main__":
q = multiprocessing.Queue()
p1 = multiprocessing.Process(target=exchange1, args=(q,))
p2 = multiprocessing.Process(target=exchange2, args=(q,))
p1.start()
p2.start()
while True:
out = q.get()
print("out is {}".format(out))
输出:
out is [1, 2, 3, 4, 5]
out is [1, 2, 3, 4, 5]
out is [4, 5, 6, 7, 8]
out is [1, 2, 3, 4, 5]
out is [1, 2, 3, 4, 5]
out is [4, 5, 6, 7, 8]
请注意,如果您还想使用
getch
要在中读取字符,必须在父进程中的单独线程中侦听从队列返回的数据,并使用curses库中的一些线程安全机制来更新UI:
def waiter(q):
while True:
out = q.get()
print("out is {}".format(out))
# Update UI in a thread-safe way
if __name__ == "__main__":
q = multiprocessing.Queue()
p1 = multiprocessing.Process(target=exchange1, args=(q,))
p2 = multiprocessing.Process(target=exchange2, args=(q,))
p1.start()
p2.start()
t = threading.Thread(target=waiter, args=(q,))
t.daemon = True
t.start()
while True:
char = window.getch()
# Other stuff