python threading lock RLock

Lock最低级的指令锁,lock获得锁定时,处于同步锁定状态,不锁定时处于等待状态

import threading
import time
data=0
lock=threading.Lock()
def func():
    global data
    print'%s current thread acquire thread'%threading.currentThread().getName()
    if lock.acquire():
        print'%s current thread acquire thread'%threading.currentThread().getName()
        time.sleep(1)
        data+=1
        print'%s current thread acquire thread'%threading.currentThread().getName()
        lock.release()
thr1=threading.Thread(target=func)
thr1.start()
thr2=threading.Thread(target=func)
thr2.start()
thr3=threading.Thread(target=func)
thr3.start()    

RLock可重入锁,被同一个线程请求多次,RLock时候被某一线程拥有,可以重复的acquire,但是acquire的次数必须和release的次数一致。RLock拥有了递归等级的概念。。。。

import threading
import time
data=0
rlock=threading.RLock()
def func():
    global data
    print'%s current thread acquire thread'%threading.currentThread().getName()
    if rlock.acquire():
        print'%s current thread acquire thread'%threading.currentThread().getName()
        time.sleep(1)
        data+=1
        if rlock.acquire:
            print'%s current thread acquire thread'%threading.currentThread().getName()
            time.sleep(1)
    print'%s current thread acquire thread'%threading.currentThread().getName()
    rlock.release()
    time.sleep(5)
    print'%s current thread acquire thread'%threading.currentThread().getName()
    rlock.release()
    time.sleep(5)
            
thr1=threading.Thread(target=func)
thr1.start()
thr2=threading.Thread(target=func)
thr2.start()
thr3=threading.Thread(target=func)
thr3.start()  

报错:没有锁定的锁释放不了

解决方法:可以做个if判断将锁释放。

Condition条件变量

构造方法Condition(Lock/RLock)当处于多个condition时候可以使用一把相同的锁,要是不自己设定,系统会默认建立一把RLock。还具有等待池,当处于等待的时候,线程全部处于等待状态,使用notify()或者notifyall()方法唤醒

实例方法:acquire(),release(),notify(),notifyAll()

Timer(定时器),是Thread的衍生类,给定时间的thread,没有实例方法

Timer(interval,target,args,kwargs)

local Thread-local线程-属性字典,可以将名字看成一个key,其线程的属性看成value,对于任何一个名字无法访问其他线程的属性数据

import threading
import time
local=threading.local()
local.tname='main'
def Name():
    local.tname='notMain'
    time.sleep(5)
thr=threading.Thread(target=Name)
thr.start()
thr.join
print(local.tname)

结果是main,线程阻塞之后回到主线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值