37,743
社区成员




class consumer(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.setName("new" + self.name)
def run(self):
global queue
while queue.qsize() > 0:
msg = self.name + ' consumer ' + queue.get()+ "get Queue Size: "+ str(queue.qsize())
print msg
time.sleep(5)
class produce(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.setName("new"+self.name)
def run(self):
global queue
b = os.path.exists(".\\testFile\\")
if b:
print "File direction Exist!"
else:
os.mkdir(".\\testFile\\")
while True:
for i in range(1, 1 + 1):
localTime = time.strftime("%Y%m%d%H%M%S", time.localtime())
filename = ".\\testFile\\" + localTime + ".txt"
f = open(filename, 'ab')
testnote = 'test file'
f.write(testnote)
f.close()
queue.put(filename)
print "file" + " " + str(i) + ":" + str(localTime) + ".txt"+ "put Queue Size: "+ str(queue.qsize())
time.sleep(1)
#print "ALL Down"
time.sleep(1)
def threadTest():
p = produce()
c = consumer()
p.start()
c.start()
p.join()
c.join()
if __name__ == '__main__':
threadTest()
class consumer(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.setName("new" + self.name)
def run(self):
global queue
while queue.qsize() > 0:
msg = self.name + ' consumer ' + queue.get()+ "get Queue Size: "+ str(queue.qsize())
print msg
time.sleep(5)
应该是 while queue.qsize() > 0 这句出了问题, 估计是线程都同时,启动了,消费者里的 queue的大小 为0了,所以没打印消息出来
# producer_consumer_queue
from Queue import Queue
import random
import threading
import time
# Producer thread
class Producer(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.data = queue
def run(self):
for i in range(5):
print "%s: %s is producing %d to the queue!\n" % (time.ctime(), self.getName(), i)
self.data.put(i)
time.sleep(random.randrange(10) / 5)
print "%s: %s finished!" % (time.ctime(), self.getName())
# Consumer thread
class Consumer(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.data = queue
def run(self):
for i in range(5):
val = self.data.get()
print "%s: %s is consuming. %d in the queue is consumed!\n" % (time.ctime(), self.getName(), val)
time.sleep(random.randrange(10))
print "%s: %s finished!" % (time.ctime(), self.getName())
# Main thread
def main():
queue = Queue()
producer = Producer('Pro.', queue)
consumer = Consumer('Con.', queue)
producer.start()
consumer.start()
producer.join()
consumer.join()
print 'All threads terminate!'
if __name__ == '__main__':
main()