Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Lock Variable Synchronization Mechanism

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Prerequisites – Process Synchronization
A lock variable provides the simplest synchronization mechanism for processes. Some noteworthy points regarding Lock Variables are- 

  1. Its a software mechanism implemented in user mode, i.e. no support required from the Operating System.
  2. Its a busy waiting solution (keeps the CPU busy even when its technically waiting).
  3. It can be used for more than two processes.

When Lock = 0 implies critical section is vacant (initial value ) and Lock = 1 implies critical section occupied.
The pseudocode looks something like this – 

Entry section - while(lock != 0);
                Lock = 1;
//critical section
Exit section - Lock = 0;

A more formal approach to the Lock Variable method for process synchronization can be seen in the following code snippet :

C




char buffer[SIZE];
int count = 0,
    start = 0,
    end = 0;
struct lock l;
 
// initialize lock variable
lock_init(&l);
 
void put(char c)
{
 
    // entry section
    lock_acquire(&l);
 
    // critical section begins
    while (count == SIZE) {
 
        lock_release(&l);
        lock_acquire(&l);
    }
 
    count++;
    buffer[start] = c;
    start++;
 
    if (start == SIZE) {
 
        start = 0;
    }
 
    // critical section ends
    // exit section
    lock_release(&l);
}
 
char get()
{
 
    char c;
 
    // entry section
    lock_acquire(&l);
 
    // critical section begins
    while (count == 0) {
 
        lock_release(&l);
        lock_acquire(&l);
    }
 
    count--;
    c = buffer[end];
    end++;
 
    if (end == SIZE) {
 
        end = 0;
    }
 
    // critical section ends
    // exit section
    lock_release(&l);
 
    return c;
}


C++




#include <mutex>
#include <condition_variable>
 
char buffer[SIZE];
int count = 0,
    start = 0,
    end = 0;
 
std::mutex mtx;
std::condition_variable cv;
 
void put(char c)
{
    std::unique_lock<std::mutex> lock(mtx);
 
    while (count == SIZE) {
        cv.wait(lock);
    }
 
    count++;
    buffer[start] = c;
    start++;
 
    if (start == SIZE) {
        start = 0;
    }
 
    cv.notify_all();
}
 
char get()
{
    std::unique_lock<std::mutex> lock(mtx);
 
    while (count == 0) {
        cv.wait(lock);
    }
 
    count--;
    char c = buffer[end];
    end++;
 
    if (end == SIZE) {
        end = 0;
    }
 
    cv.notify_all();
 
    return c;
}


Here we can see a classic implementation of the reader-writer’s problem. The buffer here is the shared memory and many processes are either trying to read or write a character to it. To prevent any ambiguity of data we restrict concurrent access by using a lock variable. We have also applied a constraint on the number of readers/writers that can have access.
Now every Synchronization mechanism is judged on the basis of three primary parameters : 

  1. Mutual Exclusion.
  2. Progress.
  3. Bounded Waiting.

Of which mutual exclusion is the most important of all parameters. The Lock Variable doesn’t provide mutual exclusion in some cases. This fact can be best verified by writing its pseudo-code in the form of an assembly language code as given below.

1. Load Lock, R0 ; (Store the value of Lock in Register R0.)
2. CMP R0, #0 ; (Compare the value of register R0 with 0.)
3. JNZ Step 1 ; (Jump to step 1 if value of R0 is not 0.)
4. Store #1, Lock ; (Set new value of Lock as 1.)
Enter critical section
5. Store #0, Lock ; (Set the value of lock as 0 again.)

Now let’s suppose that processes P1 and P2 are competing for Critical Section and their sequence of execution be as follows (initial value of Lock = 0) –

  1. P1 executes statement 1 and gets pre-empted.
  2. P2 executes statement 1, 2, 3, 4 and enters Critical Section and gets pre-empted.
  3. P1 executes statement 2, 3, 4 and also enters Critical Section.

Here initially the R0 of process P1 stores lock value as 0 but fails to update the lock value as 1. So when P2 executes it also finds the LOCK value as 0 and enters Critical Section by setting LOCK value as 1. But the real problem arises when P1 executes again it doesn’t check the updated value of Lock. It only checks the previous value stored in R0 which was 0 and it enters critical section.
This is only one possible sequence of execution among many others. Some may even provide mutual exclusion but we cannot dwell on that. According to murphy’s law “Anything that can go wrong will go wrong“. So like all easy things the Lock Variable Synchronization method comes with its fair share of Demerits but its a good starting point for us to develop better Synchronization Algorithms to take care of the problems that we face here. 

FAQ

Q: Are lock variables the best synchronization mechanism in all scenarios?
A: No, while lock variables are a simple mechanism for synchronization, they may not be efficient in scenarios where processes are frequently contending for access to a critical section. In such cases, other synchronization mechanisms like semaphores, monitors, or message passing may be more appropriate.

Q: Can lock variables cause starvation?
A: Yes, lock variables can cause starvation if a process is blocked indefinitely while waiting for access to the critical section. To prevent starvation, techniques like aging or priority inversion can be employed.

Q: Can lock variables be used in conjunction with other synchronization mechanisms?
A: Yes, lock variables can be used in conjunction with other synchronization mechanisms to provide more robust synchronization solutions. For example, a lock variable can be used to implement mutual exclusion while a semaphore can be used to implement a bounded buffer.

This article is contributed by Siddhant Bajaj 2. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Last Updated : 22 Apr, 2023
Like Article
Save Article
Similar Reads