如何在Python中的多个线程和进程之间有效地共享数据?

Yan*_*ick 6 python multithreading multiprocessing

我有一个主线程Cmd从运行cmd2threading.Thread()这使我能够使用“实时”执行模拟来交互地启动新线程。每个时间步的模拟结果是put() in a multiprocessing.Queue(). Additionally I can start live plots using matplotlib.animate. I read matplotlib is not thread-safe, so the plots run as a multiprocessing.Process() and get() the simulation results from the queue.

Unfortunately, once items from the queue are collected, they are deleted from the queue and not available for other threads or processes. This means I can send data from the simulation threads to the plotting processes, but can't use the simulation results at the same time in my main thread.

A solution could be to have two queues in each simulation thread: one queue to the main thread and one queue to the plotting process. This doesn't seem to be the optimal solution, but a rather complicated one.

有谁知道如何实现某种线程安全的共享变量,每个线程和进程都可以读取和写入?

Lie*_*yan 3

一般来说,线程和内存之间共享数据主要有两种方式:

  • 消息传递
  • 共享内存

Python 鼓励您避免编写使用共享内存的代码,如果您需要在线程和进程之间共享数据,您应该只复制数据并通过队列发送它。

如果您需要实际的共享内存,这会充满许多危险,因为您必须需要处理锁以避免出现问题。此外,对于许多 python 对象来说这可能是不可能的,因为进程中的所有 python 对象共享一个 GIL。

我读到 matplotlib 不是线程安全的

非多线程安全的代码通常也不是多进程安全的。

有谁知道如何实现某种线程安全的共享变量,每个线程和进程都可以读取和写入?

您不想,或者如果确实必须的话,也可以使用数据库。

  • 虽然我同意这个答案的大部分观点,但我确实认为“不是多线程安全的代码通常也不是多进程安全的”这句话是非常正确的。函数不是线程安全的主要原因是共享全局状态(即全局变量和文件等)。通常,进程之间有更强的隔离,因此它们甚至不会共享全局变量或临时文件。因此,大多数时候,代码很可能是多进程安全的,而不是线程安全的。 (3认同)