did you mean that one thread will be given a random time to sleep while the other is running? |
It depends on the implementation, really. Typically, though, you can expect it to sleep in relatively small intervals between polling the mutex. Or it might have an "alarm" which wakes up all threads (or a single thread of its choosing) that is currently sleeping waiting for the mutex. These kinds of details are generally out of your control though. However the threading implementation does it, that's what you're stuck with.
Did you mean that they are out of my control ever |
Out of your control in every threading lib I've ever seen, used, or heard about.
There are simply too many factors for you to reliably have this kind of control. The OS is juggling not only threads in your program, but all sorts of other threads in other processes. When you consider that you only have two cores on your machine, but possibly have dozens or even hundreds of threads running at any given time -- all of which need occasional attention -- you simply can't make such demands of the OS.
There are ways to make your threads take turns, though. Like maybe have another variable to track which thread is supposed to execute a job next. It gets tricky, though, and it usually isn't worth it.
I can't remember now, to be timed so that other thread can enter the critical section eventhough if the first thread didn't complete its critical section's execution. If I can control that, would you please show me a prototype code that demonstrate this issue? |
Some APIs have the ability to "time out" a mutex lock, so that instead of sleeping until the mutex can be locked (ie: potential deadlock if the mutex is never able to be locked) it will give up after a certain period of time (typically a few milliseconds).
HOWEVER: failure to lock a mutex is a big deal. And you should not proceed as normal. The whole point of putting things behind a mutex is that they
cannot be accessed by multiple threads at the same time. If your mutex lock failed, you don't have this guarantee, and therefore you should abort whatever task you were attempting to do.
EDIT:
I can't really give you example code on this -- as I'm not at all familiar with WinAPI threads, and don't really feel like looking it up. Sorry =(
EDIT2:
Removed my really, really poor example. It wouldn't have worked at all like I originally thought it would.