Thread-Level Parallelism and Synchronization Issues
Thread-Level Parallelism and Synchronization Issues
Thread-Level Parallelism and Synchronization Issues
Synchronization Issues
1
Data Races and Synchronization
• Two memory accesses form a data race if from
different threads to same location, and at least
one is a write, and they occur one after another
• If there is a data race, result of program can vary
depending on chance (which thread ran first?)
• Avoid data races by synchronizing writing and
reading to get deterministic behavior
• Synchronization done by user-level functions that
rely on hardware synchronization instructions
2
Lock and Unlock Synchronization
• Lock used to create region Set the lock
(critical section) where only
one thread can operate Critical section
• Given shared memory, use (only one thread
memory location as gets to execute
synchronization point: lock or this section of
semaphore
code at a time)
• Thread reads lock to see if it
must wait, or OK to go into e.g., change
critical section (and set to shared variables
locked)
– 0 => lock is free / open /
Unset the lock
unlocked / lock off
– 1 => lock is set / closed /
3
locked / lock on
Possible Lock/Unlock Implementation
• Unlock:
sw $zero,lock($s0)
4
Possible Lock Problem
• Thread 1 • Thread 2
addiu $t1,$zero,1
Loop: lw $t0,lock($s0)
addiu $t1,$zero,1
Loop: lw $t0,lock($s0)
bne $t0,$zero,Loop
bne $t0,$zero,Loop
Lock: sw $t1,lock($s0)
Lock: sw $t1,lock($s0)