Serial 36- Python thread quantity, Timer, reentrant lock

First, allow a maximum of resources to carry out simultaneously by several threads

Command line: threading.Semaphore (number)

Up to now there are representatives of several threads can operate

 

Import Threading 

Import Time 

# parameter defines the maximum number of threads can use the resource 

semaphore = threading.Semaphore (. 3) # herein refers to a maximum of three threads may operate 

DEF FUNC (): 

    IF Semaphore.acquire (): 

        for I in Range (2 ): 

            Print (. threading.current_thread () getName () + " GET semapore " ) 

        the time.sleep ( . 5 ) 

        semaphore.release () 

        Print (. threading.current_thread () getName () + " Release semaphore " ) 

for I in Range (. 8):

    t1 = threading.Thread(target=func,args=())

    t1.start()

 

Two, Timer explain

Format: threading.Timer (interval function)

This function represents the start time after "time interval"

 

def func2():

    print("I am running.....")

    time.sleep(3)

    print("I an done.......")

if __name__ == "__main__":

    t2 = threading.Timer(6,func2) #代表6秒之后开始启动线程func2

    t2.start()

    i = 0

    while True:

        print("{0}*********".format(i))

        time.sleep(3)

        i += 1

 

Third, the reentrant lock

1. A lock can be multiple applications for a thread

2. The main solution when the recursive call, oh, if necessary to apply the lock, can be locked to prevent re-apply

 

class MyThread(threading.Thread):

    def run(self):

        global num

        time.sleep(1)

        if mutex.acquire(1):

            num = num+1

            msg = self.name + " set num to "+str(num)

            print(msg)

            mutex.acquire()

            mutex.release()

            mutex.release()

def test():

    for i in range(5):

        t3 = MyThread()

        t3.start()

 

if __name__== " __main__ " : 

    NUM = 0 

    the mutex = threading.RLock () # reentrant lock 

    test ()

 

Explanation: We can thread directly, not because of a request, it will be blocked, can still apply for the lock

 

Fourth, the source

d25_4_Rlock.py

https://github.com/ruigege66/Python_learning/blob/master/d25_4_Rlock.py

2.CSDN: https: //blog.csdn.net/weixin_44630050 (Xi Jun Jun Moods do not know - Rui)

3. Park blog: https: //www.cnblogs.com/ruigege0000/

4. Welcomes the focus on micro-channel public number: Fourier transform, backstage reply "gifts" to get big data learning materials

 

Guess you like

Origin www.cnblogs.com/ruigege0000/p/11489375.html