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,线程阻塞之后回到主线程