wnat to replace thread_specific_ptr with thread_local

447 views
Skip to first unread message

earth...@gmail.com

unread,
Nov 25, 2016, 4:47:47 AM11/25/16
to ISO C++ Standard - Discussion
Hi,

what are the member functions for thread_local. I am trying to compare with boost::thread_specific_ptr. 

How do I know whether data is already exist or not. I didn't find any isSet(), setValue(), getValue(), or reset() for thread_local. In some examples, synchronizing thread using lock before reading thread_local variable.


 54 #include <iostream>
 55 #include <string>
 56 #include <thread>
 57 #include <mutex>
 58
 59
 62
 63 class testcls
 64 {
 65 public:
 66   void write(int x)
 67   {
 68     l = x;
 69   }
 70   void read()
 71   {
 72     std::cout << "val: " << l << std::endl;
 73   }
 74
 75 private:
 76   int  l;
 77 };
 78 typedef std::shared_ptr<testcls> testclsptr;
 79 static thread_local testclsptr threadVaribale;



int main()
{
   threadVaribale = std::shared_ptr<testcls> (new testcls);

}

void thr1()
{
    threadVaribale->write(5);
}

void thr2()
{
        //Do I need to add mutex before read? this is tls variable.
    threadVaribale->read();
}


Nicol Bolas

unread,
Nov 25, 2016, 9:22:55 AM11/25/16
to ISO C++ Standard - Discussion
On Friday, November 25, 2016 at 4:47:47 AM UTC-5, ED wrote:
Hi,

what are the member functions for thread_local. I am trying to compare with boost::thread_specific_ptr. 

`thread_local` is not a type; it is a storage class, like `static`. It does not have "member functions".
 
How do I know whether data is already exist or not.

If the variable has been initialized for a thread, then it already exists.
 
I didn't find any isSet(), setValue(), getValue(), or reset() for thread_local. In some examples, synchronizing thread using lock before reading thread_local variable.

I don't know why anyone would synchronize (explicitly) a thread_local variable. By definition, you cannot access such a variable from another thread. Or more to the point, each thread gets its own value for thread_local variables. Yes, you can pass another thread a pointer/reference to a thread_local. But otherwise, such synchronization does not make sense.


`main` assigned `threadVariable` a non-nullptr value. However, that can only have happened within the main thread (since you cannot call `main` from another function, nor can you pass a pointer to `main` to a `std::thread`). Therefore, the version of that variable local to the main thread is the one which has that value.

If `thr1` is called from the main thread, then it will work. If it is called from some other thread, and that thread has not given it a non-nullptr value, then it will crash. Same goes for `thr2`.

You don't need a mutex; you simply need to have given the variable a reasonable value within that thread.
Reply all
Reply to author
Forward
0 new messages