Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #17357

Re: Make a small function thread safe

Subject Re: Make a small function thread safe
From Tim Wintle <tim.wintle@teamrubber.com>
References <10d3d04f-1708-4942-8e69-92b715f01ff8@p20g2000vbm.googlegroups.com> <1324042394.23801.6.camel@tim-laptop> <CAF-oDbFg_yuMB=vgz8ZhmWHxTqY7A7JOkXFWbERyioHvLa=h2Q@mail.gmail.com>
Organization Team Rubber
Date 2011-12-16 14:36 +0000
Newsgroups comp.lang.python
Message-ID <mailman.3730.1324046183.27778.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Make a small function thread safe Brad Tilley <kj4eit@gmail.com> - 2011-12-16 05:21 -0800
  Re: Make a small function thread safe Tim Wintle <tim.wintle@teamrubber.com> - 2011-12-16 13:33 +0000
  Re: Make a small function thread safe Tim Wintle <tim.wintle@teamrubber.com> - 2011-12-16 14:36 +0000
    Re: Make a small function thread safe Brad Tilley <kj4eit@gmail.com> - 2011-12-16 07:05 -0800
  Re: Make a small function thread safe Lie Ryan <lie.1296@gmail.com> - 2011-12-17 09:08 +1100
    Re: Make a small function thread safe John Nagle <nagle@animats.com> - 2011-12-16 18:18 -0800
      Re: Make a small function thread safe RangerElf <gustavo.cordova@gmail.com> - 2011-12-18 00:52 -0800
        Re: Make a small function thread safe Ian Kelly <ian.g.kelly@gmail.com> - 2011-12-18 23:57 -0700
  Re: Make a small function thread safe ting@thsu.org - 2011-12-19 15:56 -0800

csiph-web