Python子线程阻塞父线程

时间:2015-10-18 16:41:21

标签: python multithreading

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

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平行的MainThread线程?

1 个答案:

答案 0 :(得分:0)

由于GIL,Python threading.Thread不是CPU密集型繁忙循环的好选择。根据{{​​3}}

  

全局解释器锁或GIL是一个防止多重锁定的互斥锁   本机线程一次执行Python字节码。这个锁是   必要的主要是因为CPython的内存管理不是   线程安全的。

如果您需要繁忙循环,请切换到thread.multiprocessing stblib(https://wiki.python.org/moin/GlobalInterpreterLock)以让OS调度程序处理时间片分配。来自文档

  

多处理包提供本地和远程并发,   通过使用有效地侧翻全局解释器锁   子进程而不是线程。

相关问题