Home  >  Article  >  Backend Development  >  Code example for thread synchronization primitives in python

Code example for thread synchronization primitives in python

不言
不言forward
2018-11-20 16:06:092987browse

This article brings you code examples about thread synchronization primitives in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The Threading module is a multi-threading module in python3. The module integrates many classes, including Thread, Condition, Event, Lock, Rlock, Semaphore, Timer, etc. The following article mainly uses cases to illustrate the use of Event and Segmaphore (Boundedsegmaphore).

Event

#Event class internally stores a flags parameter to mark whether the event is waiting or not.

Event class instance function

1. set() Set flags to True, the event stops blocking

2. clear() Reset flags to False, delete flags , the event is re-blocked

3. wait() sets the event to the waiting state

4.is_set() determines whether flags is set, returns True if it is set, otherwise returns False

(1) A single event waits for the occurrence of other events

Specific code:

from time import ctime,sleep
event = Event()

def event_wait():
    print(ctime())
    event.wait()
    print('这是event_wait方法中的时间',ctime())

def event_set(n):
    sleep(n)
    event.set()
    print('这是event_set方法中的时间', ctime())

thread1 = Thread(target=event_wait)
thread2 = Thread(target=event_set,args=(3,))

thread1.start()
thread2.start()

Result:

Sat Nov 17 10:01:05 2018
这是event_wait方法中的时间 Sat Nov 17 10:01:08 2018
这是event_set方法中的时间  Sat Nov 17 10:01:08 2018

(2) Multiple events occurred one after another

Let’s take racing as an example. Assume that there are 5 runways, each with one athlete, ABCDE.

Specific code:

from threading import Event
from  threading import Thread
import threading

event = Event()

def do_wait(athlete):
    racetrack = threading.current_thread().getName()
    print('%s准备就绪' % racetrack)
    event.wait()
    print('%s听到枪声,起跑!'%athlete)

thread1 = Thread(target=do_wait,args=("A",))
thread2 = Thread(target=do_wait,args=("B",))
thread3 = Thread(target=do_wait,args=("C",))
thread4 = Thread(target=do_wait,args=("D",))
thread5 = Thread(target=do_wait,args=("E",))

threads = []
threads.append(thread1)
threads.append(thread2)
threads.append(thread3)
threads.append(thread4)
threads.append(thread5)

for th in threads:
    th.start()

event.set()  #这个set()方法很关键,同时对5个线程中的event进行set操作

Result:

Thread-1准备就绪
Thread-2准备就绪
Thread-3准备就绪
Thread-4准备就绪
Thread-5准备就绪
E听到枪声,起跑!
A听到枪声,起跑!
B听到枪声,起跑!
D听到枪声,起跑!
C听到枪声,起跑!

Yes It can be seen that the set() of events in multiple threads is random, and its internal implementation is due to a notify_all() method. This method will release all locked events at once. Whichever thread grabs the time slice of thread running first will release the lock first.

The reason why all events can be exit blocked by calling only one set() function is because event.wait() is implemented inside the thread, while the set() function is called in the process. Python multi-threads share a process memory space. This cannot be achieved if these two functions are called in different processes.

BoundedSegmaphore

If the host performs IO-intensive tasks and then executes a program that completes a large number of tasks (multi-threading) in a short time, the computer will have It will most likely be down.

At this time, you can add a counter function to this program to limit the number of threads at a point in time. Every time you perform an IO operation, you need to request a resource (lock) from the segmaphore. If it is not requested, it will block and wait. Only when the request is successful is it like executing the task.

The difference between BoundedSegmaphore and Segmaphore

The number of locks requested by BoundedSegmaphore is fixed to the passed-in parameters, while the number of locks requested by Segmaphore can exceed the passed-in parameters.

Main functions:

1. acquire() Request lock

2. release() Release lock

The following is an example of renting a house to illustrate this A mechanism to fix the number of locks. Suppose a small apartment has 6 rooms and is originally occupied by 2 residents.

Specific code implementation:

from threading import BoundedSemaphore,Lock,Thread
from time import sleep
from random import randrange

lock = Lock()
num = 6
hotel = BoundedSemaphore(num)

def logout():
    lock.acquire()
    print('I want to logout')
    print('A customer logout...')
    try:
        hotel.release()
        print('Welcome again')
    except ValueError:
        print('Sorry,wait a moment.')
    lock.release()

def login():
    lock.acquire()
    print('I want to login')
    print('A customer login...')
    if hotel.acquire(False):
        print('Ok,your room number is...')
    else:
        print('Sorry,our hotel is full')
    lock.release()

#房东
def producer(loops):
    for i in range(loops):
        logout()
        print('还剩%s' % hotel._value, '房间')
        sleep(randrange(2))
#租客
def consumer(loops):
    for i in range(loops):
        login()
        print('还剩%s' % hotel._value, '房间')
        sleep(randrange(2))
def main():
    print('Start')
    room_num = hotel._value
    print('The hotel is full with %s room'%room_num)
    #原本有2个住户
    hotel.acquire()
    hotel.acquire()
    thread1 = Thread(target=producer,args=(randrange(2,8),))
    thread2 = Thread(target=consumer,args=(randrange(2,8),))
    thread1.start()
    thread2.start()

if __name__ == '__main__':
    main()

Result:

The hotel is full with 6 room
I want to logout
A customer logout...
Welcome again
还剩5 房间
I want to logout
A customer logout...
Welcome again
还剩6 房间
I want to login
A customer login...
Ok,your room number is...
还剩5 房间
I want to login
A customer login...
Ok,your room number is...
还剩4 房间

It can be seen that the number of rooms It will never exceed 6, because the _value value (the counter inside the BoundedSegmaphore) must be the incoming parameter 6.

The above is the detailed content of Code example for thread synchronization primitives in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete
Previous article:What is a python crawlerNext article:What is a python crawler