跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • Python2.7 线程结束后的函数调用
未分類
19 4 月 2021

Python2.7 线程结束后的函数调用

Python2.7 线程结束后的函数调用

資深大佬 : QBugHunter 6

首先是个线程类

class MyThread(threading.Thread):      allName = []          def __init__(self):         threading.Thread.__init__(self)              def run(self):         pass          def printMyName(self, nm):         self.allName.append(nm)         for n in self.allName:             print n 

然后有个类会回调用该函数,类似观察者模式

class OB      funPtr = []          def __init__(self):         print "请不要初始化该类"              @classmethod     def registerPtr(cls, ptr):         funPtr.append(ptr)              @classmethod     def callBackPtr(cls, nm):         for ptr in cls.funPtr:             ptr(nm) 

然后 OB 类回不断有下列调用

A = MyThread() OB.register(A.printMyName) A.start() # 线程运行结束 OB.callBackPtr("Jack")  # 这个调用时,线程类对象 A 已经运行完了 

我想问下,这种情况下,线程 A 的 run 函数以及跑完的情况下,OB 类再调用对象 A 的 printMyName ()安全吗?

另外我想了一个方案,测试可行,但我不确定是否有问题,首先再 OB 类加了一个 unregister()函数

 @classmethod def unregister(cls, ptr):     index = -1     for p int cls.funPtr:         if p == ptr:             break         index += 1     if index != -1:         del cls.funPtr[index] 

然后在线程的 run 函数最后加一句

OB.unregister(self.printMyName) 

大佬有話說 (0)

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具