简体   繁体   English

从Python中的多个线程中剔除

[英]Pickling from multiple threads in Python

I have a python program with multiple threads. 我有一个包含多个线程的python程序。 Each thread detects events, which I would like to store somewhere so that I can read them in again (for testing). 每个线程检测事件,我想将其存储在某处,以便我可以再次读取它们(用于测试)。 Right now, I'm using Pickle to output the events, and each thread outputs to a different file. 现在,我正在使用Pickle输出事件,每个线程输出到不同的文件。 Ideally, I would only use one output file, and all the threads would write to it, but when I try this, it looks like the various threads try to write their output at the same time, and they don't get pickled properly. 理想情况下,我只使用一个输出文件,并且所有线程都会写入它,但是当我尝试这个时,看起来各个线程试图同时写入它们的输出,并且它们没有被正确地腌制。 Is there a way to do this? 有没有办法做到这一点?

seems like a good place to use a Queue . 似乎是使用Queue的好地方。

  • Have all your event detection threads put items on a shared Queue. 让所有事件检测线程将项目放在共享队列上。
  • Create another thread to get items from the queue, and write/pickle/whatever from this thread. 创建另一个线程以从队列中获取项目,并从此线程中写入/ pickle /中的任何内容。

from the Queue docs: 来自队列文档:

"The Queue module implements multi-producer, multi-consumer queues. 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. It depends on the availability of thread support in Python; see the threading module." “Queue模块实现了多生产者,多用户队列。当在多个线程之间必须安全地交换信息时,它在线程编程中特别有用。该模块中的Queue类实现了所有必需的锁定语义。它取决于可用性Python中的线程支持;请参阅线程模块。“

Yes, with threading.Lock() objects. 是的,使用threading.Lock()对象。 You create a lock before creating all your threads, you give it to the method that is responsible of saving/pickling items, and this method should acquire the lock before writing into the file and releasing it after. 您在创建所有线程之前创建一个锁,然后将其提供给负责保存/ pickle项的方法,并且此方法应在写入文件并在之后释放之前获取锁。

Here is an example using threading.Lock() : 以下是使用threading.Lock()的示例:

import threading
import pickle
picke_lock = threading.Lock()
   def do(s):
       picke_lock.acquire()
       try:
           ps = pickle.dumps(s)
       finally:
           picke_lock.release()
       return ps

t1 = threading.Thread(target=do, args =("foo",))
t2 = threading.Thread(target=do, args =("bar",))
p1 = t1.start()
p2 = t2.start()

inpt = raw_input('type anything and click enter... ')

你可以创建一个锁,并在每次调用pickle.dump()获取/释放它。

The logging module has a Rlock built into its Handlers. 日志记录模块在其处理程序中内置了一个Rlock So you could logging as normal (just create a handler to log to a file.) 所以你可以正常logging (只需创建一个处理程序来登录文件。)

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

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