python学习笔记五(python多线程)

上一篇简单的介绍了下多进程,对python的并发有了一定的了解, 再将多线程相对来说就相对容易,主要就是说明下threading的用法以及线程锁。

1、threading

import threading
mylock = threading.RLock()
num=0
class myThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.t_name = name

    def run(self):
        global num
        while True:
            mylock.acquire()
            print 'Thread(%s) locked, Number: %d'%(self.t_name, num)
            if num>=100:
                mylock.release()
                print 'Thread(%s) released, Number: %d'%(self.t_name, num)
                break
            num+=1
            print 'Thread(%s) released, Number: %d'%(self.t_name, num)
            mylock.release()

if __name__== '__main__':
    thread1 = myThread('A')
    thread2 = myThread('B')
    thread1.start()
    thread2.start()
threading跟multiprocessing模块类似,主要是讲下面的线程同步。插一句,有事可能会用到Timer对象处理一些定时操作

timer = threading.Timer(5.0,func)
timer.start()

2、线程同步

A、Locke和RLocke对象

两者的用法一样,RLock的用法前面的代码有介绍,这里主要是说下两者的区别:RLock允许在同一线程中被多次acquire,而Lock却不允许这种情况,如果使用RLock,那么acquire和release必须成对出现。

B、Condition
Python的Condition对象提供了对复制线程同步的支持。使用Condition对象可以在某些事件触发后才处理数据。Condition对象除了具有acquire方法和release的方法外,还有wait方法、notify方法、notifyAll方法等用于条件处理。

import threading
import time

class Producer(threading.Thread):
    def run(self):
        global count
        while True:
            if con.acquire():
                if count > 1000:
                    con.wait()
                else:
                    count = count+100
                    msg = self.name+' produce 100, count=' + str(count)
                    print msg
                    con.notify()
                con.release()
                time.sleep(1)

class Consumer(threading.Thread):
    def run(self):
        global count
        while True:
            if con.acquire():
                if count < 100:
                    con.wait()
                else:
                    count = count-3
                    msg = self.name+' consume 3, count='+str(count)
                    print msg
                    con.notify()
                con.release()
                time.sleep(1)

count = 500
con = threading.Condition()

def test():
    for i in range(2):
        p = Producer()
        p.start()
    for i in range(5):
        c = Consumer()
        c.start()
        
if __name__ == '__main__':
    test()


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值