4

just to be clear i dont have a specific example because using the way various "how to"'s suggested to implement suited my needs until now and i did not encounter any problems regarding locks, but the usage of locks in python did raise the following question

it seems that calling lock.acquire() does not require specifying a resource to lock which made me wonder how do python locks know which object or resource to lock?

import time import thread


def myfunction(string,sleeptime,lock,*args):
    while 1:    #entering critical section
        lock.acquire() 
        print string," Now Sleeping after Lock acquired for ",sleeptime
        time.sleep(sleeptime) 
        print string," Now releasing lock and then sleeping again"
        lock.release()  #exiting critical section
        time.sleep(sleeptime) # why?


lock=thread.allocate_lock()
thread.start_new_thread(myfunction,("Thread No:1",2,lock))
thread.start_new_thread(myfunction,("Thread No:2",2,lock))
Kevin
  • 74,910
  • 12
  • 133
  • 166
user3371266
  • 69
  • 1
  • 9
  • AFAIK, locks don't lock anything but themselves. – Kevin Feb 02 '15 at 19:23
  • 3
    They don't, they just prevent themselves from being `acquire`d again until they're `release`d. – martineau Feb 02 '15 at 19:44
  • 2
    @martineau The OP posted a very relevant question and none of the Python locking/threading pages I've looked at seem to touch on this. Your comment helped me understand the concept much better. People should understand that a lock in Python isn't really locking a resource, it's locking _a section of code_ and not allowing anyone else to execute it before it's done with it. That way you have a single lock that can apply to an arbitrary number of resources, functions, etc. – Pedro Dec 01 '15 at 15:36
  • 1
    @Pedro: Nice to hear that. Locks are also called _mutex_ (mutual exclusion) objects because they allow multiple threads to synchronise access to shared resource(s) by preventing simultaneously code execution that accesses it (or them). – martineau Dec 01 '15 at 18:05

1 Answers1

0

Its cooperative locking. The lock only works for a resource to the extent that all code within the program agrees to obtain the lock before using the resource.

tdelaney
  • 73,364
  • 6
  • 83
  • 116