Python子线程阻止父线程

Python子线程阻止父线程,python,multithreading,Python,Multithreading,我有一个需要连续运行的主线程,它应该为接收到的每个数据创建新的处理器线程,它们也应该连续运行,但我的问题是,主线程的run函数只运行一次,子线程在主线程运行时阻塞了线程 import threading threads = [] class MainThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) #some functions here de

我有一个需要连续运行的主线程,它应该为接收到的每个数据创建新的处理器线程,它们也应该连续运行,但我的问题是,主线程的run函数只运行一次,子线程在主线程运行时阻塞了线程

import threading

threads = []

class MainThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    #some functions here

    def run(self):
        while True:
            print "main"
            #do some stuff
            data = ""
            client = Client()
            if data == "something":
                c = 0
                found = False
                while not found and c<len(threads):
                    if threads[c].client == client:
                        threads[c].doSomeStuff(data)
                        found = True
                    
                if not found:
                    DataHandler(data, client)

class DataHandler(threading.Thread):
    def __init__(self, data, client):
        threading.Thread.__init__(self)
        self.data = data
            self.client = client
        global threads
        threads.append(self)
 
    def doSomeStuff(self, data):
        self.data = data
        #some IO and networking stuff
    
    #some functions here

    def run(self):
        while True:
            if data is not None:
                print "data"
            #do some stuff with data

MainThread().start()
我的输出是:

主要

资料

资料

资料

如何启动与主线程并行的DataHandler线程?

Python线程。由于GIL,线程不是CPU密集型繁忙循环的好选择。据

全局解释器锁(GIL)是一个互斥锁,用于防止多个 本机线程无法同时执行Python字节码。这把锁坏了 主要是因为CPython的内存管理不是必需的 线程安全

如果需要忙循环,请切换到thread.multiprocessing stblib,让OS调度器处理时间片分配。从文件中

多处理包提供本地和远程并发, 通过使用 子进程而不是线程


子线程启动后,主线程的某些条件是否保持为真?因为当它被写入时,while循环将在子线程上连续调用start。此外,它似乎是一个占用100%CPU的忙循环,因为它连续运行,没有等待、睡眠或I/O操作。它根据数据而变化,这只是一个简单的例子。如果您的DataHandler也在忙循环中消耗所有CPU,那么执行主线程的机会很小。。。把更现实的代码,以便我们可以帮助。否则看起来还可以…看起来很有帮助,但是我可以作为一个进程启动一个类吗?如果它已经启动了,我可以调用它的函数吗?如果可能的话,你能给我举一个小例子来做一些我在进程中解释过的事情吗?我真的很感激。