sync lock

'''
GIL: Global Interpretation Lock
  Because of the GIL, only one thread is executed by the cpu at the same time
    Processing method: multi-process + coroutine
Task Type: IO Intensive
     computationally intensive
For IO-intensive tasks, Python's multithreading makes sense
          Can use multi-process + coroutine
For computationally intensive tasks, Python's multi-threading is not recommended, and Python is not suitable.
'''


#Sync    lock 
import threading
 import time


def sub():
    global  num

    lock.acquire() #Add   synchronization lock 
    temp = num
    time.sleep(0.0005)
    num = temp -1 
    lock.release() #release 
lock num = 100



l = []
lock = threading.Lock() #Create a lock

for i in range(100):
    t = threading.Thread(target=sub)
    t.start()
    l.append(t)

for i in l:
    i.join()

print (num)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325257903&siteId=291194637