只要调用这个线程的程序在跑,那么这个线程类只new一次,调用这个线程的类会不定时的向队列线程中推入新的线程,调用的类把线程推入到这个队列线程中后它就不管了.
队列线程感觉可以用个list,直接把其他的新线程加进来,写个函数对item in list一直跑,找到了就把那个线程从list里拿掉。。。是不是挺简单的感觉。。
理想很性感,实现好骨感。。。。。可惜就实现不了。。。
目前我写的程序如下:
#!encoding:utf-8
import os, sys
import Queue
import threading
# queue = Queue.Queue(0)
class parent:
link = []
def __init__(self):
self.MyThread(self.link).start()
def addLink(self, pid):
self.link.append(pid)
class MyThread(threading.Thread):
th_link = []
def __init__(self, link):
self.th_link = link
threading.Thread.__init__(self)
def run(self):
# current = threading.currentThread()
# print "当前正在进行的线程为:%s\n"%(current.name)
print len(self.th_link)
while True:
if len(self.th_link) > 0:
for i in range(0, len(self.th_link) - 1):
print i, self.th_link[i]
# query pid status
a = utilQu()
status = a.pidStatus(pid=self.th_link[i])
print "返回的status为:%s\n" % (status)
if status == "running":
print "没有结束"
else:
print "已经结束"
del self.th_link[i]
else:
print "没有线程"
self.join()
import random
class utilQu:
temp = ["running", "running", "running", "running", "running", "running", "running", "running", "running",
"commplate"]
def pidStatus(self, pid):
num = len(self.temp)
index = random.randint(0, num - 1)
print "utilQu中获取到的下标为:%s,值为%s" % (index, self.temp[index])
return self.temp[index]
a = parent()
a.addLink("zhang ruo xuan")
a.addLink("xing ba ke") 在此处想要做的是,在for循环中逐个遍历th_link,查询每个值在utilQu中的返回值,如果返回值为commplate则移除这个值,当th_link为空时,等待传入新值,但是我写的这个程序存在一个问题, 比如像下面的情况,我传入了两个值,但是这个线程就会一直循环查询第一个传入的值,第一个值不结束,就不会去查询第二个值,另一个问题是,当第一个值查询完毕了,程序就结束了,并没有查询第二个值,怎么样才能将这个程序改成我想要的结果?
RT-Thread
#!encoding:utf-8 import Queue import threading class parent: link = [] queue = Queue.Queue(0) def __init__(self): # self.MyThread(self.queue).start() pass def addLink(self, pid): self.queue.put(pid) self.MyThread(self.queue).start() class MyThread(threading.Thread): th_link = [] th_queue = [] def __init__(self, queue): self.th_queue = queue threading.Thread.__init__(self) def run(self): while True: if self.th_queue.qsize() > 0: pid = self.th_queue.get() m = False a = utilQu() while not m: returnType = a.pidStatus(pid=pid) if returnType == "commplate" : print "%s结束了\n"%(pid) break else : print "%s运行中....\n"%(pid) else: self.th_queue.join() import random class utilQu: temp = ["running", "running", "running", "running", "running", "running", "running", "running", "running", "commplate"] def pidStatus(self, pid): num = len(self.temp) index = random.randint(0, num - 1) # print "utilQu中获取到的下标为:%s,值为%s" % (index, self.temp[index]) return self.temp[index] a = parent() a.addLink("aaaaaaaaa") a.addLink("bbbbbbbbb") a.addLink("ccccccccc") a.addLink("ddddddddd") a.addLink("eeeeeeeee") a.addLink("fffffffff")