Make a small function thread safe

Tim Wintle tim.wintle at teamrubber.com
Fri Dec 16 09:36:20 EST 2011


On Fri, 2011-12-16 at 09:24 -0500, Brad Tilley wrote:
> So something like this then:
> 
> import threading
> 
> shared_container = []
> lock = threading.Lock()
> 
> class thread_example( threading.Thread ):
> 
>     def __init__( self ):
>         threading.Thread.__init__ (self)
> 
>     def run(t):
>         lock
>         shared_container.append(t.name)

should be:
      def run(t):
          with lock:
              shared_container.append(t.name)

(or lock.acquire() and lock.release() as you mentioned)

> # main
> 
> threads = []
> for i in xrange(10):
>     thread = thread_example()
>     threads.append(thread)
>     
> for thread in threads:
>     thread.start()

you'll either need to lock again here, or join each thread:

for thread in threads:
      thread.join()

> for item in shared_container:
>     print item 

Tim




More information about the Python-list mailing list