Home > Software engineering >  Why use thread_local inside functions?
Why use thread_local inside functions?

Time:10-30

I thought functions are thread safe if they don't modify non-local data.

My assumption is correct according to this answer. But, recently I came across this code,

int intRand(const int & min, const int & max) {
    static thread_local std::mt19937 generator;
    std::uniform_int_distribution<int> distribution(min,max);
    return distribution(generator);
}

The code left me puzzled. Why does it use thread_local if functions are already thread safe?

CodePudding user response:

The random number generators of the standard library (including the std::mt19937 used in the example) may not be used unsequenced in multiple threads. thread_local guarantees that each thread has their own generator which makes it possible to call the function unsequenced from multiple threads.

I thought functions are thread safe if they don't modify non-local data.

Static storage is non-local. This is true even when the variable with static storage duration is a local variable. The name is local; the storage is global.

CodePudding user response:

This is for clarity only.

static thread_local std::mt19937 generator;

and

thread_local std::mt19937 generator;

are the same things.

The static is cosmetic in this case. Both are static.

  •  Tags:  
  • c
  • Related