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