Discuss / Python / 我来解释一下锁

我来解释一下锁

Topic source

python的官方文档中有这么一句话:

A primitive lock is a synchronization primitive that is not owned by a particular thread when locked. 

我理解的锁是:

primitive lock锁并不属于任何一个线程,可以把它认为是一个公共变量。如果想要参与到锁的游戏规则中,则参加的线程都必须要在函数体中使用acquire()release()两种方法(一旦有线程不遵守该规则将会打破该平衡)。

  • acquire()

    查询锁状态,如锁是locked状态,则同步堵塞;如锁是unlocked状态,则将其上锁。

  • release()

    解锁

上述概念可用以下代码解释

import threadingimport timeLOCK = Falsedef run_thread_1():    global LOCK    while LOCK:        print("run_thread_1 is waiting")        time.sleep(1)    LOCK = True    print("run_thread_1 lock the LOCK")    print("run_thread_1 is doing something")    time.sleep(5)    LOCK = False    print("run_thread_1 release the LOCK")def run_thread_2():    global LOCK    while LOCK:        print("run_thread_2 is waiting")        time.sleep(1)    print("run_thread_2 lock the LOCK")    LOCK = True    print("run_thread_2 is doing something")    time.sleep(3)    LOCK = False    print("run_thread_2 release the LOCK")    task1 = threading.Thread(target=run_thread_1)task2 = threading.Thread(target=run_thread_2)task1.start()task2.start()task1.join()task2.join()print("finish")

之前提交代码的格式错误了。

请看下面这个。

import threading
import time

LOCK = Falsedef run_thread_1():
   global LOCK
   while LOCK:
      print("run_thread_1 is waiting")
      time.sleep(1)
   LOCK = True   print("run_thread_1 lock the LOCK")
   print("run_thread_1 is doing something")
   time.sleep(5)
   LOCK = False   print("run_thread_1 release the LOCK")

def run_thread_2():
   global LOCK
   while LOCK:
      print("run_thread_2 is waiting")
      time.sleep(1)
   print("run_thread_2 lock the LOCK")
   LOCK = True   print("run_thread_2 is doing something")
   time.sleep(3)
   LOCK = False   print("run_thread_2 release the LOCK")
   
task1 = threading.Thread(target=run_thread_1)
task2 = threading.Thread(target=run_thread_2)
task1.start()
task2.start()
task1.join()
task2.join()
print("finish")

  • 1

Reply