简体   繁体   English

线程如何在python中相互通信?

[英]How can threads communicate with each other in python?

I am writing two Python programs: one that runs an algorithm on a graph, and one that draws the graph using matplotlib. 我正在编写两个Python程序:一个在图形上运行算法,另一个使用matplotlib绘制图形。 How do I send a point to be graphed from the algorithm to the graphing program using Python? 如何使用Python将要绘制的点从算法发送到绘制程序?

Use the Queue module: 使用Queue模块:

The Queue module implements multi-producer, multi-consumer queues. Queue模块实现多生产者,多消费者队列。 It is especially useful in threaded programming when information must be exchanged safely between multiple threads. 当必须在多个线程之间安全地交换信息时,它在线程编程中特别有用。 The Queue class in this module implements all the required locking semantics. 此模块中的Queue类实现所有必需的锁定语义。

I see that your question is tagged multithreading , but your question seems to be defining it as multiple processes. 我看到您的问题被标记为multithreading ,但是您的问题似乎正在将其定义为多个进程。 If you have multiple processes, use Queue from the multiprocessing which "is a near clone of Queue.Queue ". 如果你有多个进程,使用Queuemultiprocessing这“是一个近乎克隆Queue.Queue ”。

If you need two way communication, use muliprocessing.Pipe . 如果需要双向通信,请使用muliprocessing.Pipe

I've done something very similar when I had matplotlib in a wxPython window. 当我在wxPython窗口中使用matplotlib时,我做了非常相似的事情。 I used pubsub and wx.CallAfter for this purpose. 我为此使用了pubsub和wx.CallAfter。 See this link for an example. 有关示例,请参见此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM