【发布时间】:2017-01-02 12:25:14
【问题描述】:
我正在尝试创建一个全局状态变量,它是在回调方法(事件处理程序)中编写的。 但是,回调会在另一个内存位置创建一个副本(深),(当然)其他方法看不到该副本。 情况是这样的
class Server:
def __init__(self):
self.callbacks=[]
#create a web server instance to listen to requests
self.app=Flask("test")
def add_callback(self, func):
self.calbacks.append(func)
self.app.add_url_rule("/test", "test", self.handle_http_request)
def handle_http_request(self):
content = request.get_json(silent=True)
for ca in self.callbacks:
ca(content)
def start_server(self):
#some stuff starting flask here...
class SomeModule:
def __init__(self):
self.ws=Server()
self.ws.add_callback(self.callback)
self.callback_called=False
def callback(self, content):
print "callback executing---"
print "var addr before callback assign: "+str(hex(id(self.callback_called)))
self.callback_called=True
print "var addr after callback assign: "+str(hex(id(self.callback_called)))
def start(self):
self.ws.start()
#send a request to the server using the request library, which invokes all the trigger
#check the state variable:
print "var addr before check: "+str(hex(id(self.callback_called)))
if (not self.callback_called):
raise Exception("error...")
if __name__ == '__main__':
sm=SomeModule()
sm.start()
那么输出是:
回调执行--- 回调分配前的 var addr:0x927910 回调分配前的 var addr:0x927930 检查前的 var addr:0x927910谁能给我建议一种方法来避免这种情况? 在 c++ 中,它清楚地知道如何访问指针和互斥锁。然而,在这里,我没有设法找到任何方法来对变量进行安全写入......
提前非常感谢!
【问题讨论】:
标签: python multithreading callback