Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!news-transit.tcx.org.uk!rt.uk.eu.org!newsfeed.xs4all.nl!newsfeed6.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.033 X-Spam-Evidence: '*H*': 0.94; '*S*': 0.00; 'brad': 0.07; 'x-mailer:evolution 2.28.3': 0.07; 'be:': 0.09; 'def': 0.13; 'subject:function': 0.16; 'then:': 0.16; 'threading': 0.16; 'threads:': 0.16; 'cc:addr:python-list': 0.16; 'wrote:': 0.18; 'cc:no real name:2**0': 0.20; '(or': 0.22; 'header:In-Reply-To:1': 0.22; 'cc:2**0': 0.24; 'import': 0.27; 'print': 0.29; 'cc:addr:python.org': 0.29; 'class': 0.29; 'lock': 0.30; 'threads': 0.30; 'fri,': 0.34; 'here,': 0.35; 'something': 0.35; 'thread': 0.37; 'either': 0.39; 'should': 0.39; 'join': 0.61; 'header:Reply-To:1': 0.71; 'reply-to:no real name:2**0': 0.72; '-0500,': 0.84; '09:24': 0.84; 'received:bethere.co.uk': 0.84; 'subject:Make': 0.96 Subject: Re: Make a small function thread safe From: Tim Wintle To: Brad Tilley In-Reply-To: References: <10d3d04f-1708-4942-8e69-92b715f01ff8@p20g2000vbm.googlegroups.com> <1324042394.23801.6.camel@tim-laptop> Content-Type: text/plain; charset="UTF-8" Organization: Team Rubber Date: Fri, 16 Dec 2011 14:36:20 +0000 Mime-Version: 1.0 X-Mailer: Evolution 2.28.3 Content-Transfer-Encoding: 7bit X-SA-Exim-Connect-IP: 87.194.110.230 X-SA-Exim-Mail-From: tim.wintle@teamrubber.com X-SA-Exim-Scanned: No (on mail.netsight.co.uk); SAEximRunCond expanded to false Cc: python-list@python.org X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.12 Precedence: list Reply-To: tim.wintle@teamrubber.com List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 44 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1324046183 news.xs4all.nl 6914 [2001:888:2000:d::a6]:51530 X-Complaints-To: abuse@xs4all.nl Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:17357 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