• Popular Now

• 13
• 15
• 27
• 9
• 9

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

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 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