python的线程和Queue

功能简介:
1.有一个已知字符串列表,将列表内容按照插入时的顺序,逐个输出

功能实现:
1.要将数据按照插入时的顺序取出,需要用到Queue,put插入,get输出
2.启动三个相同的线程,通过锁的方式,来实现Queue的数据读取
3.在主线程中创建锁,在子线程的实现方法中获取/释放锁
4.子线程在未被允许停止获取queue中的数据之前,需要一直运作,直到接收到来自主线程停止通知

 # coding=utf-8
import threading
import Queue
import time

# 主线程中set一个停止运行的标志
exitflag = 0


class MyThread(threading.Thread):
    def __init__(self, func, args):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.func(*self.args)


def getdata(name, q):
    # 当被允许一直运行时,去get数据
    while not exitflag:
        # 锁定getdata方法,确保同一时间只能有一个进程执行该方法
        thread_lock.acquire()
        # 如果queue非空,get数据
        if not q.empty():
            print name + " get data:" + q.get()
        # 释放queue
        thread_lock.release()
        # 每次获取data后,线程sleep 1秒
        time.sleep(1)


# 新建一个队列,并通过put存放数据
q = Queue.Queue()
namelist = ["one", "two", "three", "four", "five"]
for name in namelist:
    q.put(name)

# 主线程中新建一个锁,供子线程调用
thread_lock = threading.Lock()

# 创建三个子线程并启动
th1 = MyThread(getdata, args=("thread_1", q))
th2 = MyThread(getdata, args=("thread_2", q))
th3 = MyThread(getdata, args=("thread_3", q))
th1.start()
th2.start()
th3.start()

# 主线程监控,当queue非空时,一直允许子线程取数据
while not q.empty():
    pass
# 当queue为空时,通知子线程不再运行
exitflag = 1

# 等待子线程运行完毕,主线程再退出
th1.join()
th2.join()
th3.join()
print "Main thread end."

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值