Overview
Features
Download
Documentation
Community
Add-Ons & Services

[RESOLVED] Use of ThreadLocal

Please post support and help requests here.

[RESOLVED] Use of ThreadLocal

Postby karas » 05 Jul 2009, 11:34

Hi,
I'm trying to make an example of ThreadLocal use within threads by calculating Fibonacci array. Here is the Runnable class which should do all the work:
Code: Select all
class RunIsol : public Runnable
{
private:

   static ThreadLocal<long> prev1;

   static ThreadLocal<long> prev2;


public:

   static void setPrev(long p1, long p2)
   {
      *RunIsol::prev1 = p1;
      *RunIsol::prev2 = p2;
   }
   
   void run()
   {
      while (true)
      {
         long n = RunIsol::prev1.get() + RunIsol::prev2.get();
         cout << "RunIsol:n=" << n << endl;
         *RunIsol::prev1 = *RunIsol::prev2;
         *RunIsol::prev2 = n;
         Thread::sleep(100);
      }
      
   }
};

ThreadLocal<long> RunIsol::prev1;

ThreadLocal<long> RunIsol::prev2;

If this class is started without threads with
Code: Select all
   RunIsol ri;
   ri.setPrev(1, 1);
   ri.run();

everything works as expected. But if a thread is created:
Code: Select all
   RunIsol ri;
   ri.setPrev(1, 1);
   Thread t1;
   t1.start(ri);
   t1.join();

then thread locals prev1, prev2 are always set to zero and no calculation is possible. Does anyone sees where I'm making a mistake with ThreadLocal use?
Thanks
Last edited by karas on 06 Jul 2009, 09:14, edited 1 time in total.
karas
 
Posts: 5
Joined: 05 Jul 2009, 11:18
Location: Belgrade

Re: Use of ThreadLocal

Postby guenter » 05 Jul 2009, 17:35

The problem with your code should be obvious if you think about what thread local means.
You are initializing the thread local variables in the main thread, but using the thread locals in a separate thread. A thread local variable has a separate value for every thread. Therefore, the value you set in the main thread will never be visible to another thread.
guenter
 
Posts: 1138
Joined: 11 Jul 2006, 16:27
Location: Austria

Re: Use of ThreadLocal

Postby aderouineau » 05 Jul 2009, 23:46

If you consider that this issue has been resolved, please add [RESOLVED] at the beginning of the topic title.
aderouineau
 
Posts: 163
Joined: 18 May 2009, 17:38

Re: Use of ThreadLocal

Postby karas » 06 Jul 2009, 09:14

I see, thanks for the explanation.
karas
 
Posts: 5
Joined: 05 Jul 2009, 11:18
Location: Belgrade


Return to Support

Who is online

Users browsing this forum: No registered users and 1 guest

cron