Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python twisted-工厂对象线程安全吗?_Python_Multithreading_Twisted - Fatal编程技术网

Python twisted-工厂对象线程安全吗?

Python 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

下面的代码在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):
    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的回调除外),因此您不必担心同时运行多个东西