Make a small function thread safe
Brad Tilley
kj4eit at gmail.com
Fri Dec 16 09:30:26 EST 2011
On Fri, Dec 16, 2011 at 9:24 AM, Brad Tilley <kj4eit at gmail.com> wrote:
>
>
> On Fri, Dec 16, 2011 at 8:33 AM, Tim Wintle <tim.wintle at teamrubber.com>wrote:
>
>> On Fri, 2011-12-16 at 05:21 -0800, Brad Tilley wrote:
>> > 107 void increment_counter( unsigned int& counter )
>> > 108 {
>> > 109 boost::mutex::scoped_lock lock( counter_lock );
>> > 110 ++counter;
>> > 111 }
>>
>>
>> with counter_lock:
>> counter += 1
>>
>>
>> ... where counter_lock is a threading.Lock instance.
>>
>> (see docs for the threading module)
>
>
>
>
> 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)
>
> # main
>
> threads = []
> for i in xrange(10):
> thread = thread_example()
> threads.append(thread)
>
> for thread in threads:
> thread.start()
>
> for item in shared_container:
> print item
>
>
Or perhaps run should look like this instead:
def run(t):
lock.acquire()
shared_container.append(t.name)
lock.release()
That seems a bit barbaric to me, not sure.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111216/84b96b7e/attachment-0001.html>
More information about the Python-list
mailing list