2

I'm trying to have one member variable of a class thread local. However it seems that thread_local in a class has to also be static..? But static would mean that all instances of that class share that variable. I want it so there can be different instances of the class, but for 1 of the member variables there is a different variable for each thread that has access to this object.

So how can I have a class object, that can be passed around, and one of its member variables is thread_local for this instance of the class (this object), but not for all instances of the class (all objects of this type)?

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
Alasdair
  • 13,348
  • 18
  • 82
  • 138
  • 3
    Concerning threads, I'm quite paranoid. Hence, when I bundle thread-related data in a `class`, I have thread-private usage in mind. However, it's not impossible to have "thread local members" in a class. You had to make a `std::map` to achieve this. (`map` entries are stable - hence, this should work. However, retrieving an entry, inserting entries into map, and deleting entries from map should be done guarded, of course.) – Scheff's Cat Apr 27 '21 at 05:43
  • 3
    @Scheff's analysis and advice are solid. I'll just add that if performance is important, and your thread-creation circumstances are simple (e.g. you know ahead of time that you'll be creating N threads, the `ThreadLocalData` can have the same lifetime), you can have a `std::array` or `std::vector{N}` member (so contiguous and CPU-cache friendly, indexing using a incrementing `int` you pass the threads), or even the `std::map` Scheff suggests. Default-construct the `ThreadLocalData`s before spawning the threads, then there's less locking needed.... – Tony Delroy Apr 27 '21 at 05:58
  • This is for a low-level container, I can't use other containers within it. I can workaround with globals. – Alasdair Apr 27 '21 at 06:04
  • OT: Please, specify suitable _tags_ for your questions. They are quite important on SO. I've checked some of your questions and they all had the "C++" tag only. – Daniel Langr Apr 27 '21 at 06:37
  • 1
    Excellent comments above by @Scheff and by Tony Delroy (cannot @-mention both in a comment, sorry). And indeed _a thread-local instance variable_, while convenient, does not make sense in the architecture of C++ programs. Instance variables must be stored _somewhere_. Even ignoring the fact that C++ stores instance variables inside the object, for a thread-local local variable, every thread creation and destruction operation would have to create or destroy that variable. – ariels Apr 27 '21 at 06:40

0 Answers0