Question slightly in the abstract...
We have a situation where we have a struct that can be accessed by 2 or 3 threads concurrently.
We wish to signal to a thread that tries to modify the struct if it is already being modified.
e.g. The code at the moment:
thread0: struct->modify(var SomeNewState)
thread1: struct->modify(var SomeNewState)
thread2: struct->modify(var SomeNewState)
void struct::modify(var SomeNewState) {
EnterCriticalSection(&criticalSection);
change some state...
LeaveCriticalSection(&criticalSection);
}
What we would like to do is have struct::modify()
return immediately to indicate if the criticalSection is in use. That is, we don't want the other threads to wait on this criticalSection.
The reason we need to do this is that the first thread in 'wins' and we don't want the other threads to wait with what is then stale state. As long as the calls are not concurrent the state is valid (states are queued elsewhere). The changing of state itself is not a long operation, but is has real-world consequences that do take a long time (3-4s) to happen.
EDIT:
Solution is something along these lines.
int struct::modify(var SomeNewState) {
if(TryEnterCriticalSection(&criticalSection)) {
change some state...
LeaveCriticalSection(&criticalSection);
return 0;
}
else {
return 1;
}
}