Ok first I must preface this question with a disclaimer, I'm really new to threading so this may be a 'newbie' question but I searched google and couldn't find an answer. As I understand it a critical section is code that can only be accessed by one thread, the danger being one thread will overwrite a value before the other is finished and vice versa. What can you do about changes made outside of your class for example, I have a line monitoring program:
and on another thread I have something like this:
Now I'm afraid that in the first function I get currentNumber which is 5, right after that on another thread the number is set to 7 and then it rewrites the 7 to 6, ignoring the change made by the thread that set it to 7.
Is there anyway to lock provider.SetNum ber until the first function finishes? The critical section is basically the currentNumber which can be changed by many places in the program.
I hope I made myself clear, if not let me know and I will try to explain myself better.
Also I made the functions really short for the example. In reality the function is much longer and makes changes to currentNumber many times so I don't really want to put a lock around the entire function. If I lock every call to provider.SetNum ber and release it after I finish it can change during the time it is released before I lock it again to call provider.SetNum ber. Honestly I'm also worried about locking the entire function because of performance and deadlock.
Code:
int currentNumber = provider.GetCurrentNumber();
if(provider.CanPassNumber(false, currentNumber))
{
currentNumber+=2;
provider.SetNumber(currentNumber);
}
Code:
if(condition)
provider.SetNumber(numberToSet);
Is there anyway to lock provider.SetNum ber until the first function finishes? The critical section is basically the currentNumber which can be changed by many places in the program.
I hope I made myself clear, if not let me know and I will try to explain myself better.
Also I made the functions really short for the example. In reality the function is much longer and makes changes to currentNumber many times so I don't really want to put a lock around the entire function. If I lock every call to provider.SetNum ber and release it after I finish it can change during the time it is released before I lock it again to call provider.SetNum ber. Honestly I'm also worried about locking the entire function because of performance and deadlock.
Comment