我有一個主線程需要連續運行,它應該爲它接收到的每個數據創建新的處理器線程,它們也應該連續運行,但我的問題是,主線程運行函數只運行一次,子線程阻塞了主線程運行的時間。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
線程並行?
一旦子線程啓動,'somecondition'對主線程是否保持爲真?因爲正如它寫的那樣,while循環會在子線程上不斷調用'start'。此外,看起來它是一個忙碌的循環,吃了100%的CPU,因爲它連續運行,沒有等待或睡眠或I/O操作 – mguijarr
它根據數據而改變,它只是一個簡化的例子 – gereb95
如果你的'DataHandler'消耗了所有CPU忙碌循環,主線程執行的機會很小......放上更實際的代碼,以便我們可以提供幫助。否則它看起來不錯... – mguijarr