Python 多线程同步的另一种方法 Queue
来源:互联网 发布:一键加群软件 编辑:程序博客网 时间:2024/05/21 08:36
Queue队列有2个方法put和get方法put 是把共享数据放入队列,get是取出共享数据
put从队列的尾部放入,get从队列的头部读出。
Queue接受2个参数,一个是队列大小,小于1的队列大小,被认为是无限队列,另一个是同步方式,其中1为阻塞方式,0为触发异常。
其实,用Queue来达到线程同步,是非常简单的,因为Queue本省就是线程安全的。不需要额外的锁和条件变量,看例子:
#coding=utf-8
#file name is maker.py
import threading
import random
import time
class Maker(threading.Thread):
def __init__(self,threadName,shareObject):
threading.Thread.__init__(self,name=threadName)
self.shareObject=shareObject
def run(self):
for i in range(1,11):
time.sleep(random.randrange(1,4))
self.shareObject.put(i)
print "%s threading put %d" %(threading.currentThread().getName(),i)
=========================================================
#coding=utf-8
#file name is user.py
import threading
import time
import random
class User(threading.Thread):
def __init__(self,threadName,shareObject):
threading.Thread.__init__(self,name=threadName)
self.shareObject=shareObject
self.sum=0
def run(self):
for i in range(1,11):
time.sleep(random.randrange(1,4))
tempNum=self.shareObject.get()
print "%s threading get %d" %(threading.currentThread().getName(),tempNum)
self.sum=self.sum+tempNum
def display(self):
print "end sum is %d" %(self.sum)
=======================================================
#file name is test.py
from maker import Maker
from user import User
import Queue
quere=Queue.Queue()
maker1=Maker("maker",quere)
user1=User("user",quere)
user1.start()
maker1.start()
maker1.join()
user1.join()
user1.display()
print "main threading is over!"
- Python 多线程同步的另一种方法 Queue
- PYTHON多线程同步的几种方法
- 实现同步登录的另一种方法
- python Queue的多线程应用
- Python多线程编程使用Queue模块保持线程同步
- 多线程同步的方法
- 多线程同步的方法
- Python多线程3:queue
- python多线程之Queue
- python 多线程+queue
- Java多线程-线程的同步(同步方法)
- Java多线程-线程的同步(同步方法)
- Java多线程-线程的同步(同步方法)
- 多线程同步方法的区别
- 实现多线程同步的方法
- java多线程的同步方法
- 树莓派开机启动python脚本的另一种方法
- python 关于Decimal 保留小数点后尾数的另一种方法
- ATExpress 1.0.1(Python ,HWL编程工具)
- android开发,以记住用户登录密码为例说明SharedPreferences的简单应用
- java多态
- Zoner Photo Studio-全能的图片管理、查看、处理软件
- 求职受挫的15个心理反应
- Python 多线程同步的另一种方法 Queue
- Python学习记录
- 常见的链表题目及代码(很好的代码格式)
- python thread之join
- 【网络流各种模板】
- 外语学习的真实方法及误区
- QTP对象识别原理之我见
- 使用Windbg调试内核
- TinySQL 使用