If I have a variable which is assigned to at the start of the program and then the program creates a few threads and then refers to it, is it thread safe?
private int myVal
private void StartOfApp()
{
myVal = 99;
}
private void MethodCalledFromVariousThreads()
{
int i = 100;
if (i > myVal) //Is reading this variable thread safe?
{
//Do Stuff
}
}
}
Yes, this is thread safe. Because you are never writing to the variable ( I assume ) it’s data is, in essence, immutable. ( Ok, so it really is mutable because this is C#, but you get the idea ). Because of this, it will always return the same value and is thusly thread safe to read from.
If you never write to a variable, except when creating it, then it will always be thread safe to read from.