jeffbRTC
jeffbRTC

Reputation: 2069

Why use thread_local inside functions?

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?

Upvotes: 2

Views: 503

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117473

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.

Upvotes: 2

eerorika
eerorika

Reputation: 238401

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.

Upvotes: 5

Related Questions