python中线程安全的数据结构,Python是否有一个线程安全队列可以被pickle或以其他方式序列化到磁盘?...

这可以使用^{}模块来完成,但这不是世界上最优雅的事情:import copy_reg

import threading

import pickle

from Queue import Queue as _Queue

# Make Queue a new-style class, so it can be used with copy_reg

class Queue(_Queue, object):

pass

def pickle_queue(q):

# Shallow copy of __dict__ (the underlying deque isn't actually copied, so this is fast)

q_dct = q.__dict__.copy()

# Remove all non-picklable synchronization primitives

del q_dct['mutex']

del q_dct['not_empty']

del q_dct['not_full']

del q_dct['all_tasks_done']

return Queue, (), q_dct

def unpickle_queue(state):

# Recreate our queue.

q = state[0]()

q.mutex = threading.Lock()

q.not_empty = threading.Condition(q.mutex)

q.not_full = threading.Condition(q.mutex)

q.all_tasks_done = threading.Condition(q.mutex)

q.__dict__ = state[2]

return q

copy_reg.pickle(Queue, pickle_queue, unpickle_queue)

q = Queue()

q.put("hey")

d = pickle.dumps(q)

new_q = pickle.loads(d)

print new_q.get()

# Outputs 'hey'

copy_reg允许您注册helper函数或pickle和unpickle任意对象。因此,我们注册了Queue类的一个新版本,并使用helper函数在pickle之前删除所有不可拾取的Lock/Condition实例变量,并在取消拾取后将其添加回。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值