Python thread, role of with (automatically acquire and release Lock)

Python thread, role of with (automatically acquire and release Lock)

import threading
import time

num=0  #Global variables can be read and written by multiple threads to transfer data
mutex=threading.Lock() #Create a lock

class Mythread(threading.Thread):
    def run(self):
        global num
        with mutex:   #The function of with Lock is equivalent to automatically acquiring and releasing locks (resources)
            for i in range(1000000): #During locking, other threads cannot work
                num+=1
        print(num)

mythread=[]
for i  in range(5):
    t=Mythread()
    t.start()
    mythread.append(t)
for t in mythread:
    t.join()
print("game over")

'''
    with mutex:   #with means to automatically open the automatic release lock
        for i in range(1000000): #No one else can work during locking
            num+=1

    #The above and below are equivalent

    if mutex.acquire(1):#Lock success and continue to work. If you don't lock success, you'll wait all the time. 1 stands for monopoly
        for i in range(1000000): #During locking, other threads cannot work
            num+=1
        mutex.release() #Release lock
'''

python with

with__ It's from Python 2 5, which is a context management protocol. The purpose is to remove the try,except and finally keywords and the code related to resource allocation and release from the flowchart and simplify it__ try…. except…. finlally__ Processing flow of. with__ Pass__ enter__ Method, and then__ exit__ To deal with the aftermath and handle exceptions, so use__ with__ The object to be processed must have__ enter() and__ exit() these two methods. Among them__ enter__ The () method runs before the execution of the statement body (_with the code block wrapped by the statement), and the exit() method runs after the execution of the statement body. The with statement is applicable to the occasion of accessing resources to ensure that the necessary "cleaning" operation will be performed to release resources regardless of whether there are exceptions during use, such as automatic closing of files after use, automatic acquisition and release of locks in threads, etc.

Basic syntax format of With statement:

with expression [as target]:
	with_body

Parameter Description:

Expression: an expression that needs to be executed;

target: is a variable or tuple, which stores the result returned by the execution of expression expression expression. Optional parameters.

How the with statement works:

Follow closely__ with__ The following statements will be evaluated and return the value of the object__ enter__ () method is called, and the return value of this method will be assigned to the variable after the as keyword__ with__ After all the subsequent code blocks are executed, the previous returned object will be called__ exit__ () method. The key point of the with statement is that the evaluated object must have__ enter__ () and__ exit__ () these two methods, then we can implement them by ourselves__ with__ Statement handling exception.

Example code:

#encoding=utf-8

class opened(object):
    def __init__(self,filename):
        self.handle=open(filename)
        print "Resource:%s"%filename
    def __enter__(self):
        print "[enter%s]: Allocate resource."%self.handle
        return self.handle#You can return different objects
    def __exit__(self,exc_type,exc_value,exc_trackback):
        print "[Exit %s]: Free resource." %self.handle
        if exc_trackback is None:
            print "[Exit %s]:Exited without exception."%self.handle
            self.handle.close()
        else:
            print "[Exit %s]: Exited with exception raised."%self.handle
        return False # It can be omitted. The default None is also regarded as False


with opened(r'd:\\xxx.txt') as fp:
    for line in fp.readlines():
        print line

In opened__ enter__ () returns its own reference, which can be assigned to the fp variable in the as clause;

The type of return value can be set to different types according to actual needs, not necessarily the context manager object itself.

Exc for variable in exit() method_ Trackback for detection. If it is not None, it indicates that an exception has occurred and returns False, indicating that the exception needs to be handled by external code logic;

If no exception occurs, the default return value is None, which is also regarded as False in the Boolean environment. However, since no exception occurs, the three parameters of exit() are None. The context management code can detect this situation and handle it normally. The three parameters of the exit () method represent the type, value, and stack information of the exception.

Keywords: Python Back-end

Added by jeanne on Sun, 27 Feb 2022 13:24:12 +0200