我试图在集合中添加函数的引用(在公开的\u setCallback方法中)。 最后给出了答案。不知何故,它并没有为第二次尝试添加引用。源文件的链接是: http://pastebin.com/BNde5Cgr
代码如下:
import rpyc
test = ['hi']
myReferences= set()
class MyService(rpyc.Service):
def on_connect(self):
"""Think o+ this as a constructor of the class, but with
a new name so not to 'overload' the parent's init"""
self.fn = None
def exposed_setCallback(self,fn):
# i = 0
self.fn = fn # Saves the remote function for calling later
print self.fn
myReferences.add(self.fn)
#abc.append(i)
#i+=1
print myReferences
for x in myReferences:
print x
#print abc
if __name__ == "__main__":
# lists are pass by reference, so the same 'test'
# will be available to all threads
# While not required, think about locking!
from rpyc.utils.server import ThreadedServer
t = ThreadedServer(MyService, port = 18888)
t.start()
Answer:
<function myprint at 0x01FFD370>
set([<function myprint at 0x01FFD370>])
<function myprint at 0x01FFD370>
<function myprint at 0x022DD370>
set([<function myprint at 0x022DD370>,
请帮忙
如果要修改全局变量,应该在函数的顶部使用
global
语句我认为问题是因为你有一个
ThreadedServer
,它当然是多线程的。在但是,Python ^{} are not threadsafe (不允许多个线程同时访问它们),因此无论何时访问集合,都需要实现一个lock。您可以将锁与Python上下文管理器(即^{} statement )一起使用,该管理器为您处理获取/释放锁的操作,
Lock
本身一次只能由一个上下文管理器获取,从而阻止对集合的同时访问。请参见下面的修改代码:欢迎来到线程编程的世界。确保线程之间的共享锁保护数据!在
相关问题 更多 >
编程相关推荐