Concurrent Programming
Concurrent Programming
Synchronization constructs
Locks: mutual exclusion Condition variables: conditional synchronization Other primitives:
v
Semaphores
u u
Binary vs. counting Can be used for mutual exclusion and conditional synchronization
Programming Strategy
Decompose the problem into objects Object-oriented style of programming
Identify shared chunk of state Encapsulate shared state and synchronization variables inside objects
Dont manipulate shared variables or synchronization variables along with the logic associated with a thread
Shared objects:
Identify synchronization constructs
v
Create a lock/condition variable for each constraint Develop the methods using locks and condition variables for coordination
Problem constraints
Using a single lock is too restrictive
v v
Allow multiple readers at the same time but only one writer at any time Readers can access database when there are no writers Writers can access database when there are no readers/writers Only one thread can manipulate shared variables at any time
6
Specific constraints
v v v
5
Database::Write() {{ Database::Write() Wait until no readers/writers; Wait until no readers/writers; Access database; Access database; check out wake up waiting readers/writers; check out wake up waiting readers/writers; }} AR ==0; // # of active readers AR 0; // # of active readers AW ==0; // # of active writers AW 0; // # of active writers WR ==0; // # of waiting readers WR 0; // # of waiting readers WW ==0; // # of waiting writers WW 0; // # of waiting writers Condition okToRead; Condition okToRead; Condition okToWrite; Condition okToWrite; Lock lock; Lock lock;
State variables