Process Synchronization in OS

| Comments

What is a Process?

Operating system(OS) objective is to keep as many as of the computer resources as busy as possible. It is used to keep track of all the things an OS must remember about the state of user program.

Process is like a box, a complete entity in itself which does a step by step task written in program. More formally it is called program in execution.

Lets consider a very basic operating system with very least complexity. This operating system can run only one process at a time. Since, only one process is working at a time, it may happen that all the resources occupied by process will not be used at the same time. To maximize the resource utilization, we need to have entities running at the same time. For multiple entities, it is logical that either we need to have multiple process running at the same time or light weight multiple entities running inside process as a part of process. Process = Code + Allocated Resources + Book keeping information

Lets explore the second option, now consider process is like a box and it has resources inside the box. We create multiple child of process which is called thread.

Thread is a child of process and hence it will use resources of process. Theoretically, there is no limit on number of child threads a process can have but it seems logical that process should have enough resource for administrative purpose for these threads.

Once there are multiple threads they are going to ask for same resource at the same time. For example, if two children are in one room then they will always fight for same toy. Same applies to threads.

3 Issues with Sharing

  1. How to Share data?
  2. How to ensure threads in a process, executes one at a time?
  3. How to ensure proper sequencing of events?

To understand it better, lets take a real world example

Carl’s Jr. Restaurant

Process

  1. Customer arrives
  2. Employee takes order
  3. Employee cooks food
  4. Employee bag food
  5. Employee takes money
  6. Customer gets food and leaves

If a single employee is doing steps from 1-6 then all other customers have to wait in line and its going to be long wait. Instead, lets have multiple employees for taking order, cook food, bag food, take money. Each of these ‘employees’ are multiple threads on Process ‘Restaurant’. Each thread is responsible for doing specialized task.

Lets associate 3 issues in current situation

  1. What is shared data? - In step 2-3, Quantity of food. In step 3-4, how much food to bag
  2. Does sequence matters? - Cook can’t cook food until order arrives. Employee can’t bag food until it is cooked. So, sequencing matters.

Shared data can be passed for sharing either using message passing or storing that data in global memory of process and each thread read from that memory location.

The next logical question is how to ensure threads in a process executes one at a time i.e. in exclusion? More formally there are three types of solution categories

  1. Algorithmic approach
  2. Software Primitives
  3. Concurrent programming construct

Algorithmic approach

The algorithmic approach to process synchronization does not use any assistance from the computer architecture or the OS kernel. Instead it uses an arrangement of logical conditions to satisfy the desired synchronization requirements. [Dhamdhere]

Software Primitives

A set of software primitives for mutual exclusion e.g Semaphore, Locks etc. were developed to overcome the logical complexity of algorithmic implementations. This is implemented using some special architectural features of computer systems. But, ease of use and correctness still remained the major obstacle in a development of large concurrent systems.

Semaphores

It is a shared integer variable with non-negative values that have initialization, wait and signal as a indivisible operation.

Semaphore Class
 1
 2class Semaphore {
 3    public:
 4    //Constructor
 5    Semaphore(char *debugName, int initialValue);
 6
 7    //Destructor
 8    ~Semaphore();
 9
10    private:
11    int value;
12    List *waitQueue;
13    char *name;
14};
Semaphore Constructor
1
2Semaphore(char * debugName, int initialValue) {
3    name      = debugName;
4    value     = initialValue;
5    waitQueue = new List;
6}
Semaphore Destructor
1
2~Semaphore() {
3    delete waitQueue;
4}
Semaphore Wait
 1
 2//P() - Semaphore Wait
 3Semaphore::P() {
 4    //Disable interrupts
 5    IntStatus oldLevel = interrupt->SetLevel(IntOff);
 6
 7    //Semaphore not available
 8    while (value == 0) {
 9    waitQueue->Append((void *)currentThread);
10    currentThread->Sleep();
11    }
12
13    //Semaphore now availble
14    value--;
15    (void)interrupt->SetLevel(oldLevel);
16}
Semaphore Signal
 1
 2//Semaphore Signal
 3Semaphore::V() {
 4    Thread *thread;  
 5
 6    IntStatus oldLevel = interrupt->SetLevel(IntOff);
 7
 8    //Remove first thread from wait queue
 9    thread->(Thread *)waitQueue->Remove();
10
11    if (thread != NULL) {
12    scheduler->ReadyToRun(thread);  
13    }
14
15    value++;
16
17    (void)interrupt->SetLevel(oldLevel);
18}

Locks

The basic idea is to close/acquire a lock at the start of critical section or an indivisible operation and open/release it at the end of the critical section or the indivisible operation.

Locks solves how to ensure threads in a process executes one at a time but not the sequencing problem.

Lock Class

Lock Class
 1
 2class Lock {
 3    public:
 4    Lock (char *debugName);
 5    ~Lock();
 6
 7    char* getName() { return name; }
 8
 9    void acquire();
10    void release();
11    bool isHeldByCurrentThread;
12
13    private:
14    char*   name;
15    List*   lockWaitQueue;
16    bool    lockFree;
17    Thread* currentLockThread;
18};
Lock Constructor
1
2//Lock Constructor
3Lock::Lock(char * debugName) {
4    name              = debugName;
5    currentLockThread = NULL;
6    lockFree          = TRUE;
7    lockWaitQueue     = new List;
8}
Lock Destructor
1
2//Lock Destructor
3~Lock() {
4    delete lockWaitQueue;  
5}
Lock Acquire
 1
 2Lock::acquire() {
 3    //Disable interrupts
 4    IntStatus oldLevel = interrupt->SetLevel(IntOff);
 5
 6    //Check if current thread is an owner
 7    if (currentThread == currentLockThread) {
 8    //Already owner  
 9    (void)interrupt->SetLevel(oldLevel);
10    return;
11    }
12
13    if(lockFree == TRUE) {
14    lockFree = FALSE;
15    currentLockThread = currentThread;      
16    } else {
17    lockWaitQueue->Append((void*) currentThread);
18    currentThread->Sleep();
19    }
20
21    (void)interrupt->SetLevel(oldLevel);
22}
Lock Release
 1
 2Lock::release() {
 3    Thread* waitingThread;
 4    IntStatus oldLevel = interrupt->SetLevel(IntOff);
 5
 6    if (!isHeldByCurrentThread()) {
 7    //Thread is not valid owner of lock its
 8    //trying to release
 9    DEBUG("Not a lock owner");
10
11    (void)interrupt->SetLevel(oldLevel);
12    return;      
13    }
14
15    waitingThread = (Thread*)lockWaitQueue->Remove();
16
17    if (waitingThread != NULL) {
18    scheduler->ReadyToRun(waitingThread);
19    currentLockThread = waitingThread;      
20    } else {
21    lockFree = TRUE;
22    currentLockThread = NULL;
23    }
24
25    (void)interrupt->SetLevel(oldLevel);
26}
Lock Owner
1
2bool Lock::isHeldByCurrentThread() {
3    return ((currentThread != currentLockThread) ?  FALSE : TRUE);
4}

Concurrent Programming Construct

Locks can only solve mutual exclusion problem, they can not solve sequencing problem. We need another mechanism Monitors

Monitors is a programming language construct that supports both data access synchronization and control synchronization.

Monitors have 3 parts

  1. Lock for mutual exclusion
  2. 1 or more condition variables for sequencing
  3. Monitor variables for make sequencing decisions -> Shared data

Condition Variables

Each condition variable is only associated with one lock.

Condition Class
 1
 2class Condition {
 3    public:
 4    Condition(char *debugName);
 5    ~Conditon();
 6
 7    char* getName() { return name; }
 8
 9    void wait(Lock* conditionLock);
10    void signal(Lock* conditionLock);
11    void broadcast(Lock* conditionLock);
12
13    private:
14    char* name;
15    List* cvQueue;
16    Lock* cvLock;  
17};
CV Constructor
1
2Condition::Condition(char * debugName) {
3    name    = debugName;
4    cvQueue = new List;
5    cvLock  = NULL;  
6}
CV Destructor
1
2Condition::~Condition() {
3    delete cvQueue;    
4}
CV Wait
 1
 2void Condition::wait(Lock* conditionLock) {
 3    IntStatus oldLevel = interrupt->SetLevel(IntOff);
 4
 5    if (cvQueue->isEmpty()) {
 6    //This lock is now associated with CV and
 7    //only removed when last entry is removed
 8    //from cvQueue.
 9    cvLock = conditionLock;
10    }
11
12    if (conditionLock == NULL) {
13    interrupt->SetLevel(oldLevel);  
14    return;
15    }
16
17    conditionLock->release();
18    cvQueue->Append((void*) currentThread);
19    currentThread->Sleep();
20
21    //Acquire lock when get up
22    conditionLock->acquire();
23    interrupt->SetLevel(oldLevel);    
24}
CV Signal
 1
 2void Conditon::signal(Lock * conditionLock) {
 3    IntStatus oldLevel = interrupt->SetLevel(IntOff);
 4
 5    //If nobody to signal, return
 6    if (cvQueue->Empty()) {
 7    interrupt->SetLevel(oldLevel);
 8    return;
 9    }
10
11    //Verify right lock is signalled
12    if (cvLock != conditionLock) {
13    interrupt->SetLevel(oldLevel);
14    return;
15    }
16
17    thread = cvQueue->Remove();
18    if (thread != NULL) {
19    scheduler->ReadyToRun(thread);
20    }
21
22    if (cvQueue->isEmpty()) {
23    cvLock = NULL;
24    }
25
26    interrupt->SetLevel(oldLevel);
27}

Producer-Consumer Problem

Lets consider we have infinite buffer

monitor variable => int itemCount = 0;
monitor lock => monitorLock;
monitor condition => needItem;

Producer
 1
 2while (true) {
 3    monitorLock.acquire();
 4
 5    //Produce item
 6    //Put in a buffer
 7    itemCount++;
 8
 9    needItem.signal(&monitorLock);
10
11    monitorLock.Release();    
12}
Consumer
 1
 2while (true) {
 3    monitorLock.acquire();
 4
 5    while(intemCount == 0) {
 6    needItem.wait(&monitorLock);      
 7    }
 8
 9    //Buffer has atleast one item
10    itemCount--;
11
12    monitorLock.Relase();
13}

Comments