简体   繁体   中英

What is Lock in Python _thread module?

I read "Core Python Applications Programming", in which this code is written.

import _thread
from time import sleep, ctime

loops = [4, 2]

def loop(nloop, nsec, lock):
  print("start loop", nloop, "at:", ctime())
  sleep(nsec)
  print("loop", nloop, "done at:", ctime())
  lock.release()

def main():
  print("starting at:", ctime())
  locks = []
  nloops = range(len(loops))

  for i in nloops:
    lock = _thread.allocate_lock()
    a = lock.acquire()
    locks.append(lock)

  for i in nloops:
    _thread.start_new_thread(loop, (i, loops[i], locks[i]))

  for i in nloops:
    while locks[i].locked(): pass

  print("all DONE at:", ctime())

if __name__ == "__main__":
  main()

In official reference, I saw "only one thread at a time can acquire a lock". Lock is to ensure that only one thread is executed at a time, isn't it ? Now I have two questions.

  1. Why can more than one locks be produced ?
  2. Why can two thread acquire each lock at the same time ?

Re (1), you can make as many locks as you require -- presumably they're needed to protect different shared mutable resources in a many-threads environment (personally, I think a programming environment with many threads sharing many mutable resources is where programmers go after passing if they've led really terrible lives).

Re (2), "Why can two thread acquire each lock at the same time" -- they absolutely cannot , that is all that locks are about: that each lock can be held by at most one thread at any given time. The lock object is built that way using whatever underlying resources the operating system provides for the purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM