Home > Backend Development > Python Tutorial > Python multi-threaded programming 5

Python multi-threaded programming 5

高洛峰
Release: 2016-10-18 11:27:57
Original
1258 people have browsed it

Mutex lock is the simplest thread synchronization mechanism. The Condition object provided by Python provides support for complex thread synchronization issues. Condition is called a condition variable. In addition to providing acquire and release methods similar to Lock, it also provides wait and notify methods. The thread first acquires a condition variable and then determines some conditions. If the condition is not met, wait; if the condition is met, perform some processing to change the condition, and notify other threads through the notify method. Other threads in the wait state will re-judge the condition after receiving the notification. This process is repeated continuously to solve complex synchronization problems.

It can be thought that the Condition object maintains a lock (Lock/RLock) and a waiting pool. The thread obtains the Condition object through acquire. When the wait method is called, the thread releases the lock inside the Condition and enters the blocked state. At the same time, the thread is recorded in the waiting pool. When the notify method is called, the Condition object will select a thread from the waiting pool and notify it to call the acquire method to try to acquire the lock.

The constructor of the Condition object can accept a Lock/RLock object as a parameter. If not specified, the Condition object will create an RLock internally.

In addition to the notify method, the Condition object also provides the notifyAll method, which can notify all threads in the waiting pool to try to acquire the internal lock. Due to the above mechanism, threads in the waiting state can only be awakened through the notify method, so the function of notifyAll is to prevent threads from being in a silent state forever.

The classic problem that demonstrates condition variable synchronization is the producer and consumer problem: Suppose there is a group of producers (Producer) and a group of consumers (Consumer) interacting with products through a market. The producer's "strategy" is to produce 100 products and put them on the market if the remaining products on the market are less than 1,000; while the consumer's "strategy" is to produce more than 100 products on the market. Consume 3 products. The code to use Condition to solve the problem of producers and consumers is as follows:

import threading
import time
  
class Producer(threading.Thread):
    def run(self):
        global count
        while True:
            if con.acquire():
                if count > 1000:
                    con.wait()
                else:
                    count = count+100
                    msg = self.name+' produce 100, count=' + str(count)
                    print msg
                    con.notify()
                con.release()
                time.sleep(1)
  
class Consumer(threading.Thread):
    def run(self):
        global count
        while True:
            if con.acquire():
                if count < 100:
                    con.wait()
                else:
                    count = count-3
                    msg = self.name+&#39; consume 3, count=&#39;+str(count)
                    print msg
                    con.notify()
                con.release()
                time.sleep(1)
  
count = 500
con = threading.Condition()
  
def test():
    for i in range(2):
        p = Producer()
        p.start()
    for i in range(5):
        c = Consumer()
        c.start()
if __name__ == &#39;__main__&#39;:
    test()
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template