Reputation: 187
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.
Upvotes: 1
Views: 2479
Reputation: 882751
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.
Upvotes: 1