[英]Python Dictionaries and Threading Concurrency
I'm using a non-blocking asynchronous threading websockets protocol (Tornado) in python 3. I'm using a dictionary very conservatively in the global level, but it can be updated by any number of threads (basically when a new user connects, their socket is mapped to an object via the dictionary). 我在python 3中使用了非阻塞异步线程Websockets协议(Tornado)。我在全局级别上使用的字典非常保守,但是可以通过任意数量的线程进行更新(基本上是在新用户连接时,它们的套接字通过字典映射到一个对象)。 I've made a basic system to deal with concurrency... but it's not any official method.
我已经建立了一个处理并发的基本系统……但这不是任何官方方法。 Since the sockets are unique, I don't think I should have any problem with people trying to assign values to the same socket at the same time, but I was wondering if with scale, there might be another problem, such as trying to get something from the dictionary when it's being resized.
由于套接字是唯一的,所以我认为人们在尝试同时向同一套接字分配值时不会有任何问题,但是我想知道是否使用scale可能会有另一个问题,例如尝试获取调整字典大小时的内容。 For reference, here's the "concurrency-fix" I came up with.
作为参考,这是我想到的“并发修复程序”。
class Routing_Table:
def set(self, key, value):
self.blocked = self.blocked + 1
self.table[key] = value
self.blocked = self.blocked - 1
def get(self, key):
while(self.blocked > 0):
pass
return self.table[key]
def __init__(self):
self.table = {}
self.blocked = 0
EDIT: Also, do you think I should add a method similar to set for deleting entries? 编辑:另外,您认为我应该添加一种类似于设置删除条目的方法吗?
If you want to do anything in a thread-safe manner, the basic idea is: 如果要以线程安全的方式执行任何操作,则基本思想是:
class ConcurrentThingy:
def __init__ (self):
self.lock = Lock () # or RLock () if you want it to be reentrant
def concurrentlyAccessedMethod (self, *args, **kwargs):
with self.lock: doMeanStuff ()
Your class could look something like this: 您的课程可能看起来像这样:
class Routing_Table:
def set (self, key, value):
with self.lock: self.table[key] = value
def get(self, key):
with self.lock: return self.table[key]
def __init__(self):
self.table = {}
self.lock = Lock ()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.