start_new_thread内的类的start_new_thread

时间:2014-07-07 07:01:09

标签: python python-2.7

我正在尝试在另一个start_new_thread中使用start_new_thread

现在,代码的粗略布局就像这样

Main.py

....
a = Helper()
start_new_thread(a.x,()) # 1 
....

Inside Helper类

....
def x(self):
    start_new_thread(self.a,()) # 2
....

这些函数故意不是线程安全的。 问题在于,只要#2执行它就会暂时停止主线程,直到它被返回。

为什么会发生这种情况以及可以采取哪些措施来解决这个问题?

2 个答案:

答案 0 :(得分:1)

我认为是时候阅读GIL

答案 1 :(得分:1)

class KThread(threading.Thread):

 def __init__(self, *args, **kwargs):

    threading.Thread.__init__(self, *args, **kwargs)
    self.killed = False

 def start(self):

    self.__run_backup = self.run
    self.run = self.__run      # Force the Thread to install our trace.
    threading.Thread.start(self)

 def __run(self):

    sys.settrace(self.globaltrace)
    self.__run_backup()
    self.run = self.__run_backup

 def globaltrace(self, frame, why, arg):
    if why == 'call':
      return self.localtrace
    else:
      return None

 def localtrace(self, frame, why, arg):
    if self.killed:
      if why == 'line':
        raise SystemExit()
    return self.localtrace

 def kill(self):

    self.killed = True

 ###################################

class 2:
 t2 = KThread(target=function)
 t2.start()
 t2.kill()
 t3 = KThread(target=function)
 t3.start()
 t3.kill()