1010#define TR2_REGION_NESTING_INITIAL_SIZE (100)
1111
1212static struct tr2tls_thread_ctx * tr2tls_thread_main ;
13- static uint64_t tr2tls_us_start_main ;
13+ static uint64_t tr2tls_us_start_process ;
1414
1515static pthread_mutex_t tr2tls_mutex ;
1616static pthread_key_t tr2tls_key ;
1717
1818static int tr2_next_thread_id ; /* modify under lock */
1919
20- struct tr2tls_thread_ctx * tr2tls_create_self (const char * thread_name )
20+ void tr2tls_start_process_clock (void )
21+ {
22+ if (tr2tls_us_start_process )
23+ return ;
24+
25+ /*
26+ * Keep the absolute start time of the process (i.e. the main
27+ * process) in a fixed variable since other threads need to
28+ * access it. This allows them to do that without a lock on
29+ * main thread's array data (because of reallocs).
30+ */
31+ tr2tls_us_start_process = getnanotime () / 1000 ;
32+ }
33+
34+ struct tr2tls_thread_ctx * tr2tls_create_self (const char * thread_name ,
35+ uint64_t us_thread_start )
2136{
22- uint64_t us_now = getnanotime () / 1000 ;
2337 struct tr2tls_thread_ctx * ctx = xcalloc (1 , sizeof (* ctx ));
2438
2539 /*
@@ -29,7 +43,7 @@ struct tr2tls_thread_ctx *tr2tls_create_self(const char *thread_name)
2943 */
3044 ctx -> alloc = TR2_REGION_NESTING_INITIAL_SIZE ;
3145 ctx -> array_us_start = (uint64_t * )xcalloc (ctx -> alloc , sizeof (uint64_t ));
32- ctx -> array_us_start [ctx -> nr_open_regions ++ ] = us_now ;
46+ ctx -> array_us_start [ctx -> nr_open_regions ++ ] = us_thread_start ;
3347
3448 ctx -> thread_id = tr2tls_locked_increment (& tr2_next_thread_id );
3549
@@ -55,7 +69,7 @@ struct tr2tls_thread_ctx *tr2tls_get_self(void)
5569 * here and silently continue.
5670 */
5771 if (!ctx )
58- ctx = tr2tls_create_self ("unknown" );
72+ ctx = tr2tls_create_self ("unknown" , getnanotime () / 1000 );
5973
6074 return ctx ;
6175}
@@ -124,22 +138,18 @@ uint64_t tr2tls_absolute_elapsed(uint64_t us)
124138 if (!tr2tls_thread_main )
125139 return 0 ;
126140
127- return us - tr2tls_us_start_main ;
141+ return us - tr2tls_us_start_process ;
128142}
129143
130144void tr2tls_init (void )
131145{
146+ tr2tls_start_process_clock ();
147+
132148 pthread_key_create (& tr2tls_key , NULL );
133149 init_recursive_mutex (& tr2tls_mutex );
134150
135- tr2tls_thread_main = tr2tls_create_self ("main" );
136- /*
137- * Keep a copy of the absolute start time of the main thread
138- * in a fixed variable since other threads need to access it.
139- * This also eliminates the need to lock accesses to the main
140- * thread's array (because of reallocs).
141- */
142- tr2tls_us_start_main = tr2tls_thread_main -> array_us_start [0 ];
151+ tr2tls_thread_main =
152+ tr2tls_create_self ("main" , tr2tls_us_start_process );
143153}
144154
145155void tr2tls_release (void )
0 commit comments