python中的多线程

使用多线程处理列队数据。这样的话,就可以不断的给子线程发送数据由子线程处理了。

#!/usr/bin/env python

# -*- coding: utf-8 -*-

from Queue import Queue  

import threading  

import time  


class Consumer(threading.Thread):  

    def __init__(self, t_name, queue,cond):  

        threading.Thread.__init__(self, name=t_name)  

        self.data=queue   

        self.condition = cond

    def run(self):

        while(True):

            self.condition.acquire()

            if not self.data.empty():  

                xtmp = self.data.get()

                print 'size thread=',self.data.qsize()

                print 'qeue=%d'%(xtmp)

        self.condition.release()  

 

#Main thread  

def main():  

    queue = Queue()  

    con = threading.Condition()

    consumer = Consumer('Con.', queue,con)  

    consumer.setDaemon(True)

    consumer.start()

    while(True):

        time.sleep(2)

        if queue.empty():

            queue.put(99)

            queue.put(98)

            queue.put(97)

            print 'size main=',queue.qsize()

            print 'xxxx'

        

    print 'All threads terminate!'  

if __name__ == '__main__':  

    main()

输出结果:

size main=size thread=  2

qeue=99

size thread= 1

2qeue=98

size thread= 0


xxxx

qeue=97

size main=size thread=  22

qeue=99

size thread= 1

qeue=98

size thread= 0

qeue=97


xxxx

size main= 3size thread=

xxxx

 2

qeue=99

size thread= 1

qeue=98

size thread= 0

qeue=97

size main= 3size thread= 2

qeue=99


。。。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值