[New-bugs-announce] [issue11866] race condition in threading._newname()

Peter Saveliev report at bugs.python.org
Mon Apr 18 13:29:02 CEST 2011


New submission from Peter Saveliev <svinota.saveliev at gmail.com>:

The _newname() function has no locking.

It is called from the new thread constructor. Such constructor is executed within parent thread. So, when several threads create new threads simultaneously, there can be race condition, leading to the same name for two (or even more) threads.

8<--------------------------------

>>> import threading
>>> import dis
>>> dis.dis(threading._newname)
403           0 LOAD_GLOBAL              0 (_counter)
              3 LOAD_CONST               1 (1)
              6 BINARY_ADD         
              7 STORE_GLOBAL             0 (_counter)

404          10 LOAD_FAST                0 (template)
             13 LOAD_GLOBAL              0 (_counter)
             16 BINARY_MODULO      
             17 RETURN_VALUE       
>>> 
8<--------------------------------

The race condition can be achieved between BINARY_ADD and STORE_GLOBAL. Several threads can do BINARY_ADD before the first one will do STORE_GLOBAL. All racing threads will get the same name.

8<--------------------------------
$ for i in `seq 0 100`; do python thread_test.py |\
 awk -F Thread- '{print $2}' |\
 grep -vE '^$' |\
 sort |\
 uniq -c -d; done
      2 35
      2 12
      ...
8<--------------------------------

As you see, there are cases when several threads can get same name.

Proposals: use thread-safe increment counter (with atomic get-increment) like itertools.counter() (that does not release GIL)

----------
components: Extension Modules
files: thread_test.py
messages: 133963
nosy: Peter.Saveliev
priority: normal
severity: normal
status: open
title: race condition in threading._newname()
type: behavior
versions: Python 2.6
Added file: http://bugs.python.org/file21704/thread_test.py

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11866>
_______________________________________


More information about the New-bugs-announce mailing list