Sign in to follow this  

Thread Safety

This topic is 4867 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

One question. Is it thread safe to use static variables, and return them by reference in member functions, considering the variables won't persist outside of the function past the calling line of code? More specifically, how and when does the OS decide to switch thread processing from one thread to another within a program? This is what I want to do more or less, so I don't have to set Result.y every function call to the same value. Is it thread safe? I'm worried, that perhaps if Result was being accessed in one thread, and then Result was modified in another thread, then the first thread would get the wrong value.
class A
{
   int x, y;
};

class B
{
   static A Result;
   A& Func(int Param)
   {
      Result.x=Param;
      return Result;
   }
   B()
   {
      Result.y=3;
   }
};

Same thing if I did something like this:
class A
{
   int x, y;
   A(int Param) : y(Param)
};

class B
{
   A& Func(int Param)
   {
      static A Result(3);
      Result.x=Param;
      return Result;
   }
};

Also, say in the first case I had multipule functions return the same piece of data. Could that cause irregular values to appear in multi-threaded programs?

Share this post


Link to post
Share on other sites
just skimmed your code but what you described is not safe, you have no control over when the OS decides to switch to the second thread, it may be half way in a function or something.

you might want to take a look at semaphores with which you can implement thread synchronization

Share this post


Link to post
Share on other sites
Ok, I was always unsure about how the schedular handled threads and processes, ty.

Well really the only reason I wanted to use static variables was so the amount of data used in each class was kept to a bare minimum. I know it's silly to be memory concious with the relatively simple programs I make, but I guess it's best to start now then when it actually matters.

Share this post


Link to post
Share on other sites

This topic is 4867 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this