courses:cs334-201503:lectures:locksandthreads.pptx (194.7 KB)

Download Report

Transcript courses:cs334-201503:lectures:locksandthreads.pptx (194.7 KB)

Threads and Synchronization
•We’ve seen several ways to start threads
• Extend the thread class
• Implement “runnable” interface
• Thread Pools – start a bunch of threads via
• Executor Service
Threads and Synchronization
• Also, several flavors of synchronization, With
Synchronized keyword
• Synchronize a method
• Synchronize a code block (less than a full method)
• Synchronization essentially provides mutex lock
capability.
Threads and Synchronization
• What kind of synchronization should be used?
• Locking is a necessary evil – it slows down other threads,
while protecting thread-shared variables/data
• Contention – Threads or processes waiting for a lock to
be granted. Avoid contention. Minimize contention
when it cannot be avoided.
• So:
• Use whatever provides data protection/integrity and
minimizes contention
• Use whatever relates to the task that is needed.
• Ask: Do we have Dependent or Independent tasks?
Threads and Notifications
“you may have already won!”
• We’ve also seen Producer Consumer models where:
• Threads wait for a condition to occur
• Indefinitely, or with a timeout value
• Threads notify (none/one/all) threads that a condition has
occurred: notify(), notifyAll()
• wait()/notify() must be called from within a synchronized
method or code block
• wait()/notify() are methods of the Object class
• All objects have support for wait and notify and are always called
with an object reference (this works)!
What’s next in the world of threads?
• More on the Lock interface and explicit locks
• Along with condition variables
• Semaphores
• General case of a mutex lock
• Atomicity
• What makes all this synchronicity work at
the OS level?
• Deadlocks
• Detection and avoidance
Explicit locks and Condition Variables
• Explicit locks use the ReentrantLock() class.
• Explicit locks utilize condition variables.
• wait() notify() are coupled with an associated
synchronized lock
• POSIX Standard: mutex lock, condition variable are
separate entities
• One can mix and match locks and condition variables.
• More efficient if > 1 notification objects & 1 sync. lock
• Condition variables implement the Condition interface
Semaphores
• Semaphores – similar to lock interface
• Consider: a mutex lock is a special case of a
semaphore
• Semaphores have a count associated with them: instead
of one marble in a bowl, there can be many marbles
• Actually called permits
• Lock interface uses lock() and unlock()
• Semaphore interface uses acquire() and release()
• Acquire and release permits
Atomicity, Deadlocks
• Coming soon