2-8 Semaphore Event Timer

A semaphore

Semaphore is a lock, you can specify the semaphore of 5, compared to the same time a mutex only one task to perform to grab the lock, semaphore at the same time can have five tasks to perform to get the lock, if mutually exclusive lock is shared houses who try to steal a toilet, then the signal is equivalent to the amount of competition for a group of passers public toilets, pit latrines have more bits, which means that at the same time can have multiple personal public toilets, public toilets to accommodate the number is certain, this is the size of the semaphore

from threading import Thread,Semaphore
import threading
import time

def func():
    sm.acquire()
    print('%s get sm' %threading.current_thread().getName())
    time.sleep(3)
    sm.release()

if __name__ == '__main__':
    sm=Semaphore(5)
    for i in range(23):
        t=Thread(target=func)
        t.start()

Resolve

Semaphore管理一个内置的计数器,
每当调用acquire()时内置计数器-1;
调用release() 时内置计数器+1;
计数器不能小于0;当计数器为0时,acquire()将阻塞线程直到其他线程调用release()。

Two Event

A key feature is that each thread is a separate thread running and an unpredictable state. If other threads in the program need to determine their next action by judging the state of a thread, then thread synchronization problem will become very difficult. To solve these problems, we need to use the Event object threading library. Object contains a set of threads by a signal flag that allows a thread to wait for the occurrence of certain events. In the initial case, the signal Event object flag is set to false. If there is a thread to wait for an Event object, and the sign of the Event object is false, then the thread will be blocked until the flag has been true. If one thread will signal an Event object flag is set to true, it wakes up all the threads waiting for this Event object. If a thread is waiting for a true Event has been set as the object, then it will ignore the event, continue

from threading import Event

event.isSet():返回event的状态值;

event.wait():如果 event.isSet()==False将阻塞线程;

event.set(): 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态, 等待操作系统调度;

event.clear():恢复event的状态值为False。

Event

For example, there are multiple threads attempt to link the work of MySQL, we want to make sure MySQL before linking normal service only for those who work thread to connect to the MySQL server, if the connection is not successful, we will try to reconnect. Then we can use threading.Event mechanism to coordinate the operation of each worker thread connection

from threading import Thread,Event
import threading
import time,random
def conn_mysql():
    count=1
    while not event.is_set():
        if count > 3:
            raise TimeoutError('链接超时')
        print('<%s>第%s次尝试链接' % (threading.current_thread().getName(), count))
        event.wait(0.5)
        count+=1
    print('<%s>链接成功' %threading.current_thread().getName())


def check_mysql():
    print('\033[45m[%s]正在检查mysql\033[0m' % threading.current_thread().getName())
    time.sleep(random.randint(2,4))
    event.set()
if __name__ == '__main__':
    event=Event()
    conn1=Thread(target=conn_mysql)
    conn2=Thread(target=conn_mysql)
    check=Thread(target=check_mysql)

    conn1.start()
    conn2.start()
    check.start()

Three timer

Timer, designated to perform certain operations after n seconds

from threading import Timer

def hello():
    print("hello, world")

t = Timer(1, hello)
t.start()  # after 1 seconds, "hello, world" will be printed

Guess you like

Origin www.cnblogs.com/shibojie/p/11664804.html