There's only one soda machine and it's a shared resource. Think about if you had a soda vending machine. Semaphores are good for producer/consumer situations where producers are allocating resources and consumers are consuming them. Semaphores can be used similarly, but I think they're better used when you have a shared resource that can be available and unavailable based on some integer number of available things. I generally use synchronization variables like this when I have one or more threads waiting on a single particular condition (e.g. When the queue is empty, it can call syncVar.signal() to wake up a random thread that is sitting asleep on syncVar.wait() (or there's usually also a signalAll() or broadcast() method to wake up all the threads that are waiting). Presumably, you'll have a thread somewhere else that is pulling things out of the queue. ![]() Why not instead have a synchronization variable that can be signaled to tell the thread that the resource is available? //pseudocode The problem with this is that you're wasting processor time by having this thread repeatedly check the condition. For instance, if you have a thread (or multiple threads) that can't continue onward until a queue is empty, the busy waiting approach would be to just doing something like: //pseudocode ![]() They can be used for similar purposes.Ī condition variable is generally used to avoid busy waiting (looping repeatedly while checking a condition) while waiting for a resource to become available. Semaphores and condition variables build on top of the mutual exclusion provide by locks and are used for providing synchronized access to shared resources. You could theoretically use a binary semaphore to do this, but that's a special case. When you want to ensure that a piece of code is atomic, put a lock around it.
0 Comments
Leave a Reply. |