添加函数不适用于Python中的set

2024-10-01 00:35:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在集合中添加函数的引用(在公开的\u setCallback方法中)。 最后给出了答案。不知何故,它并没有为第二次尝试添加引用。源文件的链接是: http://pastebin.com/BNde5Cgr

http://pastebin.com/aCi6yMT9

代码如下:

    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>,

请帮忙


Tags: theimportselfcomhttpfunctionatfn
2条回答

如果要修改全局变量,应该在函数的顶部使用global语句

def exposed_setCallback(self, fn):
    global myReferences
    # i = 0
    self.fn = fn  # Saves the remote function for calling later
    print self.fn
    myReferences.add(self.fn)

我认为问题是因为你有一个ThreadedServer,它当然是多线程的。在

但是,Python ^{} are not threadsafe(不允许多个线程同时访问它们),因此无论何时访问集合,都需要实现一个lock。您可以将锁与Python上下文管理器(即^{} statement)一起使用,该管理器为您处理获取/释放锁的操作,Lock本身一次只能由一个上下文管理器获取,从而阻止对集合的同时访问。请参见下面的修改代码:

import rpyc
import threading
test = ['hi']
myReferences= set()
myReferencesLock = threading.Lock()
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
    with myReferencesLock:
        myReferences.add(self.fn)
    #abc.append(i)
    #i+=1
    with myReferencesLock:
        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()

欢迎来到线程编程的世界。确保线程之间的共享锁保护数据!在

相关问题 更多 >