Python twisted-工厂对象线程安全吗?
下面的代码在2端口上侦听,当出现修改全局dict对象的消息时。还有一个定时器也会修改dictPython twisted-工厂对象线程安全吗?,python,multithreading,twisted,Python,Multithreading,Twisted,下面的代码在2端口上侦听,当出现修改全局dict对象的消息时。还有一个定时器也会修改dict d = {} class x(Protocol): def dataReceived(self, data): # according to data call x's function self.f() def f(self): global d d['x'] = 'x' class y(Protocol): de
d = {}
class x(Protocol):
def dataReceived(self, data):
# according to data call x's function
self.f()
def f(self):
global d
d['x'] = 'x'
class y(Protocol):
def dataReceived(self, data):
# according to data call y's function
self.f()
def f(self):
global d
d['y'] = 'y'
def modify_d():
global d
for k in d.keys():
if d[k] == 'whatever':
del d[k]
reactor.listenTCP(8880, x())
reactor.listenTCP(8881, y())
lc = task.LoopingCall(modify_d)
lc.start(300)
reactor.run()
访问d时是否需要在其周围添加锁?它不是线程安全的,但这并不重要。你不需要锁。Twisted在同一个主I/O线程中运行所有回调(涉及专门提到线程的API的回调除外),因此您不必担心同时运行多个东西