6

For example:

#include <thread> thread_local int n = 1; void f() { ++n; // is n initialized here for each thread or prior to entering f()? } int main() { std::thread ta(f); std::thread tb(f); ta.join(); tb.join(); } 

It's still not entirely clear from here when is n initialized.

5
  • When the thread is initialized. Commented Feb 19, 2016 at 14:56
  • For each thread when it (the thread) is initialized. Commented Feb 19, 2016 at 14:57
  • 1
    Related: stackoverflow.com/questions/24253584/… Commented Feb 19, 2016 at 15:08
  • It does look confusing a bit. What's local is the storage for n for each thread. But the scope of n (i.e. its visibility in code) is global. Commented Feb 19, 2016 at 16:04
  • The initialization itself takes place as the answers (here and in the linked question) describe: before its use. When exactly? Not specified by the standard. Commented Feb 19, 2016 at 16:10

1 Answer 1

6

Simple enough, and all according to specification. n is going to be initialized whenever the new thread is run - before you enter any thread-specific functions.

To be exact, it is going to be initialized three times.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.