从Python中的多个线程进行酸洗 [英] Pickling from multiple threads in Python

查看:95
本文介绍了从Python中的多个线程进行酸洗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个线程的python程序.每个线程都会检测事件,我想将其存储在某个地方,以便我可以再次读取它们(以进行测试).现在,我正在使用Pickle输出事件,每个线程将输出到一个不同的文件.理想情况下,我将只使用一个输出文件,并且所有线程都将写入该文件,但是当我尝试执行此操作时,看起来各个线程试图同时写入其输出,并且它们没有被正确地腌制.有办法吗?

I have a python program with multiple threads. 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. 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类 模块实现所有必需的锁定语义.这取决于 Python中线程支持的可用性;看到线程 模块."

"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."

这篇关于从Python中的多个线程进行酸洗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆