The problem itself:
class B{/*...*/};
class A {
/* members */
NON-static thread_local B var; // and a thread_local variable here
ret_t method(/* args */);
};
I want var
to exist independently each thread and each instance.
The larger (complete) problem:
Instances of A
are shared across threads. B is some resource necessary to call A::method
, and it must be independent with respect to threads to avoid race condition (that is, A::method
must have "write access" to var
). And the corresponding B
are different for different instances of A
.
One not fully satisfactory approach I came up with is to have some container (say std::unordered_map<THREAD_IDENTIFIER_TYPE, B>
) to store each var
corresponding to each thread
per instance. However, this neither limit access to var
s across threads nor prevent the whole container from being modified. (So that require developer to be careful enough to write safe code.)
I've seen a few post on java ThreadLocal keyword(?) on SO, but none of them seem to provide idea that really works. Any suggestion?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…