Goldman Sachs Interview Question
Software Engineer / DevelopersWhen using multiples threads you must prevent two diferents threads manipulate the same memory address, for example one thread write in one memory address and another thread read the same address, this lead to errors. To prevent this you use mutex and semaphores to lock access to diferents parts of code for diferents threads, like a semaphore, it block the execution of one thread until another until the shared part is release. But if you misuses muxes and semaphores you may lead to a deadlock, this happens when different threads block the execution of themselves, meaning that neither one of them will continue, the threads will be mutually blocking themselves. You may prevent it by the correct use of of the locks, not misuse it(good thread programming).
What Allan said is partly correct. You should use synchronization objects from preventing accidental memory changes(cause memory would be shared by threads). These are the different synchronization objects. Each one has different purpose.
- Hitesh December 18, 20101. Mutex - mutually exclusive access
2. Semaphore - Limit access to number of resources. e.g. Up to 4 threads can access to particular resource.
3. Critical Section: a piece of code that accesses a shared resource (data structure or device) that must not be concurrently accessed by more than one thread of execution.
4. Event: To notify particular action has occurred.
Now regarding Deadlock:
Avoidance, Prevention and Detection.
Deadlock avoidance and prevention are quite difficult because there are 4 conditions (Coffman conditions) which should be satisfied to prevent deadlock from happening.
1. Remove mutual exclusion
2. Remove Hold and wait
3. Provide Preemption (i.e. No-preemption would lead to deadlock
4. No circular wait (generally because of circular wait, deadlock happens)
you can read about this conditions further from internet.
Thanks.