Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#7066 closed Bugs (fixed)

Thread: An attempt to fix current_thread_tls_key static initialization order

Reported by: Pekka Seppänen <pekka.seppanen@…> Owned by: anthonyw
Milestone: Boost 1.51.0 Component: thread
Version: Boost 1.50.0 Severity: Problem
Keywords: current_thread_tls_key set_current_thread_data current_thread_tls_init_flag Cc:


Currently Boost.Thread's Win32 TLS implementation uses a static variable (thread::current_thread_tls_key) that is not defined at a function scope.

This has a certain shortcoming: As initilization order of global static variables is not predictable, it may happen that thread::current_thread_tls_key is used (via thread::set_current_thread_data()) before it is actually initialized by compiler (or the underlaying OS, to be precise). (An example: class that uses thread_specific_ptr and is not heap allocated.)

Potentially any prior versions to Boost 1.50.0 are also affected, as 1.50.0 merely changed the initial value from a zero to a non-zero value.

A proposed solution is to move thread::current_thread_tls_key inside a function scope (inside a helper function that sole purpose is to return reference to that variable). This ensures that current_thread_tls_key is initiliazed properly before it's used for the first time. As thread::set_current_thread_data() uses a static current_thread_tls_init_flag Boost.Once flag that is currently initialized at a global scope, move that flag too inside a function scope.

A patch that implements proposed solution is attached. Unfortunaly, currently no test case exists (not sure if one is too easy to be made; At least on MSVC9 global static variables are initialized before the program's entry point inside a simple loop).

Attachments (1)

boost_1_50_0_current_thread_tls_key.patch (4.2 KB) - added by Pekka Seppänen <pekka.seppanen@…> 5 years ago.
Move TLS related global static variables inside a function scope in order to ensure predictable initialization order.

Download all attachments as: .zip

Change History (3)

Changed 5 years ago by Pekka Seppänen <pekka.seppanen@…>

Move TLS related global static variables inside a function scope in order to ensure predictable initialization order.

comment:1 Changed 5 years ago by anthonyw

  • Resolution set to fixed
  • Status changed from new to closed

Fixed on trunk revision 79239

comment:2 Changed 5 years ago by viboes

  • Milestone changed from To Be Determined to Boost 1.51.0

Add Comment

Modify Ticket

Change Properties
Set your email in Preferences
as closed The owner will remain anthonyw.
The resolution will be deleted. Next status will be 'reopened'.

E-mail address and user name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.