在start_new_thread中调用类的start_new_thread

0 投票
2 回答
602 浏览
提问于 2025-04-18 12:19

我正在尝试在一个 start_new_thread 里面再使用另一个 start_new_thread

现在,代码的大致结构是这样的:

Main.py

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

在 Helper 类里面

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

这些函数故意设计成不安全的线程使用。

问题是,每当 #2 执行时,它会暂时停止主线程,直到返回。

为什么会这样?有什么办法可以解决这个问题吗?

2 个回答

0
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()

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

1

我觉得你该了解一下GIL了。

撰写回答