Init signature: threading.Event()
Docstring:
Class implementing event objects.
Events manage a flag that can be settotruewith the set() methodandresettofalsewiththeclear()method. Thewait()methodblocks(阻塞)untiltheflagistrue. Theflagisinitially(最初)false.
代码实例 :
from threading import Event,Thread
import time
import logging
FORMAT='%(asctime)s %(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT,level=logging.INFO)
defboss(event:Event,count):
logging.info('boss : I am boss, waiting for {} cups'.format(count))
event.wait()
logging.info('boss : Good job')
defworker(event:Event,count):
logging.info('worker : I am worker, working for {} cups'.format(count))
cups=[]
whileTrue:
logging.info('worker : made 1')
time.sleep(0.1)
cups.append(1)
if len(cups)==count:
event.set()
break
logging.info('worker : I have made {} cups'.format(len(cups)))
e=Event()
c=10
w=Thread(target=worker,args=(e,c))
b=Thread(target=boss,args=(e,c))
b.start()
w.start()
wait介绍 :
Signature: threading.Event.wait(self, timeout=None)
Docstring:
Block untilthe internal flag istrue.
If the internal flag istrueon entry, return immediately. Otherwise,
block until another thread calls set() tosetthe flag totrue, oruntilthe optional timeout occurs.
When thetimeout argument is present andnot None, it should be a
floating point number specifying a timeoutforthe operation in seconds
(or fractions thereof).
This method returns the internal flag onexit, so it will always return
True except if a timeoutisgivenandthe operation times out.
class lock(builtins.object)
| A lock object is a synchronization primitive. Tocreate a lock,
| call threading.Lock(). Methods are:
|
| acquire() -- lock the lock, possibly blocking until it can be obtained
| release() -- unlock of the lock
| locked() -- test whether the lockis currently locked
|
| A lockisnot owned by the thread that locked it; another thread may
| unlock it. A thread attempting to lock a lock that it has already locked
| will block until another thread unlocks it. Deadlocks may ensue(接踵而至).
|......
将1000个杯子的任务交给10个工人,代码如下:
from threading import Event,Thread,Lock
import time
import logging
FORMAT='%(asctime)s %(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT,level=logging.INFO)
cups=[]
defworker(count):
logging.info('worker : I am worker, working for {} cups'.format(count))
while len(cups)<count:
logging.info('worker : made 1')
time.sleep(0.0001)
cups.append(1)
logging.info('worker : We have made {} cups'.format(len(cups)))
for _ in range(10):
Thread(target=worker,args=(1000,)).start()
from threading import Event,Thread,Lock
import time
import logging
FORMAT='%(asctime)s %(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT,level=logging.INFO)
cups=[]
lock=Lock()
defworker(count):
logging.info('worker : I am worker, working for {} cups'.format(count))
finished=FalsewhileTrue:
# lock.acquire()with lock:
if len(cups)>=count:
finished=Truebreakifnot finished:
logging.info('worker : made 1')
time.sleep(0.0001)
cups.append(1)
logging.info('worker : We have made {} cups'.format(len(cups)))
for _ in range(10):
Thread(target=worker,args=(1000,)).start()
非阻塞锁
acquire默认为阻塞状态 ,即访问已被其它进程锁定的资源会进入等待状态
若设置为非阻塞,则不会等待
Lock().acquire(False)
RLock
RLock介绍 :
Signature: threading.RLock(*args, **kwargs)
Docstring:
Factory functionthatreturnsanewreentrant(再次进入的) lock.
A reentrant lock must be released bythe thread that acquired it.
Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking;
the thread must release it once foreachtimeit has acquired it.