Are you interested in Python? Do you know how to operate Condition in Python Library in practice? If you are interested in the operation steps of the Python Library, you can click on our article to have a better understanding of it.
Condition is a hybrid version of Lock and Event. In addition to being the basic function of Lock, it also provides wait () and Condition y () as the "Message notification" between threads ".
- from threading import *
- from time import *
- condi = Condition()
- def t1():
- condi.acquire()
- try:
- for i in range(10):
- print currentThread().name, i
- sleep(1)
- if (i == 4): condi.wait()
# Wait () releases the lock and enters the waiting state. The system tries to obtain the lock again after receiving the message sent by notify () and continues subsequent code execution.
- finally:
- condi.release()
- def t2():
- condi.acquire()
- try:
- for i in range(10):
- print currentThread().name, i
- sleep(1)
- finally:
- condi.notify()
# Notify the waiting thread to get up before releasing the lock.
- condi.release()
- Thread(target=t1).start()
- Thread(target=t2).start()
Output:
- $ ./main.py
- Thread-1 0
- Thread-1 1
- Thread-1 2
- Thread-1 3
Thread-1 4 <--- Thread1 release the lock and start waiting. Thread-2 0 <--- Thread2 get the lock and start execution.
- Thread-2 1
- Thread-2 2
- Thread-2 3
- Thread-2 4
- Thread-2 5
- Thread-2 6
- Thread-2 7
- Thread-2 8
Thread-2 9 <--- Thread2 sends a notification and releases the lock. Thread-1 5 <--- Thread1 receives the message and obtains the lock again to start unfinished work.
- Thread-1 6
- Thread-1 7
- Thread-1 8
- Thread-1 9
Wait () can actually be divided into two actions: "condi. release ();... acquire. We can use Condition to wrap the existing locks, and of course we can use with/as to improve our code.
- lock = RLock()
- condi = Condition(lock)
- def t1():
- with condi:
- for i in range(10):
- print currentThread().name, i
- sleep(1)
- if (i == 4): condi.wait()
- def t2():
- with lock:
- for i in range(10):
- print currentThread().name, i
- sleep(1)
- condi.notify()
- Thread(target=t1).start()
- Thread(target=t2).start()
Note that the threads that call Policy () and policyall () must obtain the lock beforehand. Otherwise, an exception is thrown.