Threading blocking functions

François Pinard pinard at iro.umontreal.ca
Sun Aug 20 21:59:08 EDT 2000


[Roy Katz]

> If a function is called simulatenously by different threads, will each
> thread blocand wait for the function to finish executing, or will a new
> copy of the function begin executing?

A new copy of the function begins execution.

> How can I specify either behaviour (blocking, nonblocking)?

Use locking devices.

> I wrote a piece of code with the following behaviour:

> # only one copy of this function must run at one time.
> def update( data ):
>    do-something-with-data

> # many of these are run, and they all call update(). 
> def thread():
>    # I want this to block until update() is no longer busy
>    # servicing other threads.
>    data = something
>    update( data )

The following is not tested, but I would be tempted to try:

   def update( data, lock=threading.Lock() )
      lock.acquire()
      do-something-with-data
      lock.release()

to make sure that only one copy of `update' is running at a given time.
Take a look at the 'threading' module, or at least, how it is documented
in the Library Reference manual.  I found the documentation pretty clear.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list