13.3.1 Lock/RLock 对象
如果锁处于 unlocked 状态, acquire() 方法将其修改为 locked 并返回;如果已经处于 locked 状态,则阻塞当前线程并等待其他线程释放锁,然后将其修改为 locked 并返回。release() 方法用来将 locked 锁状态修改为 unlocked 并返回,如果锁本来就是 unlocked 状态,调用该方法会抛出异常。
import time
class myThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global x
lock.acquire()
for i in range(3):
x = x + i
time.sleep(2)
print(x)
lock.release()
lock = threading.RLock() # lock = threading.Lock()
t1 = []
for i in range(10):
t = myThread()
t1.append(t)
x = 0
for i in t1:
i.start()
13.3.2 Condition 对象
使用 Condition 对象实现线程同步。
首先实现生产者线程类:
import threading
class Producer(threading.Thread):
def __init__(self, threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
global x
con.acquire()
if x == 20:
con.wait()
else:
print('\nProducer:', end = ' ')
for i in range(20):
print(x, end = ' ')
x = x + 1
print(x)
con.notify()
con.release()
实现消费者线程类:
class Consumer(threading.Thread):
def __init__(self, threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
global x
con.acquire()
if x == 0:
con.wait()
else:
print('\nConsumer:', end = ' ')
for i in range(20):
print(x, end = ' ')
con.acquire()
x = x - 1
print(x)
con.notify() # 此方法用于唤醒任何等待条件变量的线程。只有当调用线程获得锁时,才必须调用该线程
con.release()
创建 Condition 对象及生产者线程和消费者线程。
con = threading.Condition()
x = 0
p = Producer('Producer')
c = Consumer('Consumer')
p.start()
c.start()
p.join()
c.join()
print('After Producer and Consumer all done:', x)
13.3.3 queue 对象
queue 模块实现了多生产者-消费者队列,尤其适合需要在多个线程之间进行信息交换的场合。
import threading
import time
import queue
class Producer(threading.Thread):
def __init__(self, threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
global myqueue
myqueue.put(self.getName())
print(self.getName(), ' put ', self.getName(), ' to queue.')
class Consumer(threading.Thread):
def __init__(self, threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
global myqueue
print(self.getName(), ' get ', myqueue.get(), ' from queue.')
myqueue = queue.Queue()
plist = []
clist = []
for i in range(10):
p = Producer('Producer' + str(i))
plist.append(p)
c = Consumer('Consumer' + str(i))
clist.append(c)
for i in plist:
i.start()
i.join()
for i in clist:
i.start()
i.join()
13.3.4 Event 对象
Event 对象是一种简单的线程通信技术,一个线程设置 Event 对象,另一个线程等待 Event 对象。
import threading
class mythread(threading.Thread):
def __init__(self, threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
global myevent
if myevent.isSet():
myevent.clear()
myevent.wait()
print(self.getName())
else:
print(self.getName())
myevent.set()
myevent = threading.Event()
myevent.set()
t1 = []
for i in range(10):
t = mythread(str(i))
t1.append(t)
for i in t1:
i.start()