6

Let's say I have the following declaration:

thread_local std::atomic<void*> local_var;

Are modifications of local_var from other threads allowed? That is, if I communicate the address of the local_var to another thread, won't modifying local_var from there summon the nasal demons?

  • What would "thread-local" mean if they were? – Andy Prowl Jul 04 '13 at 21:49
  • That would be baaaaaaaad. – Tony Hopkinson Jul 04 '13 at 21:49
  • @TonyHopkinson Why? I would, of course, take care of lifetime issues. The address of thread-local variable does not change once it is allocated, thus fundamentally I could communicate that address to another thread and modify the variable from there with proper synchronization. –  Jul 04 '13 at 21:52
  • I've got no definite or official answer to this, but I would assume why not? Thread local variables are just a variable per thread, once you've taken a ref or pointer to it, there should be no difference between them and a normal pointer. – Mike Vine Jul 04 '13 at 22:15
  • 1
    It is of course possible and "allowed", but it does not make sense. If you want something to be modified from another thread, do not make it thread local in the first place. – Damon Jul 04 '13 at 22:15
  • 1
    @Damon well it could make sense in Master/Slave designs. But besides that I dont see any problems why this shouldnt work. TLS just differs in the way how the variables are acquired, but it still have a legit and regular memory location. – Sebastian Hoffmann Jul 04 '13 at 22:18
  • 1
    @Paranaix: Indeed, as long as you do not violate other things (such as aliasing it with a pointer of the wrong type) there is nothing "wrong" with it, and since TLS is part of the same single one address space, it must of course work, too. But it does not make sense. That's akin to locking your secret diary in your room with an extra big lock and giving everyone the key. If you don't mind others reading your diary, you need not lock it away. – Damon Jul 04 '13 at 22:21
  • 2
    @Damon As I said, a scenario I came up with are multiple slave / worker threads which have to store data thread-specific and share them at the same time with a single master thread. E.g the current task they are working on. – Sebastian Hoffmann Jul 04 '13 at 22:23
  • Why bad. Threadlocal demonstrates intent... – Tony Hopkinson Jul 05 '13 at 09:26

1 Answers1

12

Yes, it is allowed to modify another thread's thread-local variables.

What thread_local means for a variable is that the name refers to a different object in each thread, but it doesn't mean the object is private to its thread. If you make the variable known by something other than its name, i.e. its address, then other threads can access it.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521