2015-10-18 131 views
0

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

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

我的输出是:

主要

数据

数据

数据

我是如何设法开始与MainThread一个DataHandler线程并行?

+0

一旦子线程启动,'somecondition'对主线程是否保持为真?因为正如它写的那样,while循环会在子线程上不断调用'start'。此外,看起来它是一个忙碌的循环,吃了100%的CPU,因为它连续运行,没有等待或睡眠或I/O操作 – mguijarr

+0

它根据数据而改变,它只是一个简化的例子 – gereb95

+0

如果你的'DataHandler'消耗了所有CPU忙碌循环,主线程执行的机会很小......放上更实际的代码,以便我们可以提供帮助。否则它看起来不错... – mguijarr

回答

0

由于GIL,Python threading.Thread对于CPU密集型繁忙循环不是一个好的选择。根据https://wiki.python.org/moin/GlobalInterpreterLock

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

如果你需要一个繁忙的循环,切换到thread.multiprocessing stblib代替(https://docs.python.org/2/library/multiprocessing.html)有OS调度器处理时间片分配。从

多处理软件包提供了本地和远程并发的文档 有效边踩着使用 子流程,而不是线程全局解释器锁。

+0

看起来很有帮助,但我可以开始一个类作为一个过程,如果它已经开始,我可以称它为函数吗? – gereb95

+0

如果有可能,那么你能给我一个例子吗?我真的很感激它。 – gereb95