Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python start_new_线程内类的start_new_线程_Python_Python 2.7 - Fatal编程技术网

Python start_new_线程内类的start_new_线程

Python start_new_线程内类的start_new_线程,python,python-2.7,Python,Python 2.7,我正在尝试在另一个start\u new\u thread中使用start\u new\u thread 现在,代码的大致布局如下 Main.py .... a = Helper() start_new_thread(a.x,()) # 1 .... 内部助手类 .... def x(self): start_new_thread(self.a,()) # 2 .... 这些函数不是线程安全的。 问题在于,每当执行#2时,它都会暂时停止主线程,直到它返回 为什么会发生这种情况,以及

我正在尝试在另一个
start\u new\u thread
中使用
start\u new\u thread

现在,代码的大致布局如下

Main.py

....
a = Helper()
start_new_thread(a.x,()) # 1 
....
内部助手类

....
def x(self):
    start_new_thread(self.a,()) # 2
....
这些函数不是线程安全的。 问题在于,每当执行
#2
时,它都会暂时停止主线程,直到它返回


为什么会发生这种情况,以及可以采取哪些措施来克服这种情况?

我想现在是时候让您了解一下。

Python采用了一种新的方法。在任何给定的时间内,只有一个线程会运行。如果没有从多线程中逃逸出来,我必须同时使用所有这些线程,该怎么办?这样一来,函数就无法从线程中删除。这些线程是必需的,因为工作与网络相关。删除线程会导致主进程挂起,这在所有情况下都是不需要的。网络I/O是释放GIL的例外情况之一。但是,您仍然可以使用、或之类的工具在没有线程的情况下执行网络相关操作。同时,在处理多个连接的情况下,您将有更好的性能。
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()