Python中线程与队列的组合使用

#!/usr/bin/evn python

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

import threading

import multiprocessing

import Queue

import time

 

class myThread(threading.Thread):

def run(self):

print("Thread-"+self.name+" Start.........................\n")

threadActionfun(self.name,self.q)

print("Thread-"+self.name+" End..........................\n")

 

threadlock=threading.Lock();

 

messages=Queue.Queue();

 

threadNames=['thread-One','thread-Two','thread-Three']

actionlist=['one','two','three','four','fifair']

isEnd=0

"""

把需要处理的数据添加到相应的队列当中

"""

threadlock.acquire()

for actionstr in actionlist:

messages.put(actionstr);

threadlock.release();

 

def threadActionfun(name,q):

while not isEnd:

"""

使用线程锁把数据逐个拿出来

"""

q.acquire()

if not messages.empty():

messagestr = messages.get();

print("simon--" + name + " action :" + messagestr+"\n");

q.release();

time.sleep(1);

 

threads=[];

# 初始化线程数据

for threadName in threadNames:

threadobj=myThread();

threadobj.q=threadlock;

threadobj.name=threadName;

threadobj.start();

threads.append(threadobj)

 

while not messages.empty():

pass

isEnd=1;

print("已经使用IsEnd了")

 

# 等待子线程完成

for thread in threads:

thread.join();

 

print("本机cpu数量为:"+str(multiprocessing.cpu_count()))

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值