Python 多线程同步的另一种方法 Queue

本文通过Python示例介绍了如何使用Queue队列实现线程间的同步,包括put和get方法的使用,以及如何通过Queue实现线程安全的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

=======================================================

#coding=utf-8
#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!"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值