views:

62

answers:

1

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;
    }
}
+3  A: 

Are you using Windows?

TryEnterCriticalSection

[Edit: fixed link]

JimG
Ahh, truly your google-fu is superior to mine - Thanks!
Byron Ross
Actually, I just used Google to find the exact link for EnterCriticalSection, because the 'try' variant would be under the same category :)
JimG