2015-10-18 79 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