arkham knight
arkham knight

Reputation: 383

Process synchronization with semaphores

This was an interview question , any help would be appreciated

How do you synchronize two processes, out of which one is increments a value and the the displays it ( P.S. the process which displays the value must only display a value when its a new value )

Ex : int x = 5; P1 : increments it to 6 P2 : must display 6 ( only once ) and must display it again when it becomes 7

I answered that I would use a semaphore something like

int c=0; // variable that I used to synchronize


// In P1
if( c = 0 )
{
   c++;
   x++; // value that is incremented
}

// in P2
if( c == 1 )
{
   cout<<x;
   c--;
}

He then asked what would you do if there's a context switch from process P1 to P2 after setting c to 1 but before incrementing x ( As in that case it would enter P2 before incrementing x )

I couldn't answer this part. Any help would be appreciated.

Upvotes: 1

Views: 319

Answers (1)

Oleg Kuralenko
Oleg Kuralenko

Reputation: 11553

Here's a working solution in python, 2 semaphores will be needed. Note that this is a solution for a single producer/printer, in case you needed multiple producers / writers it wouldn't work

   from threading import Semaphore, Thread

    x = 0
    ITERS = 10


    def producer():
        global x
        while x < ITERS:
            s_empty.acquire()
            x += 1
            s_full.release()


    def printer():
        while x < ITERS:
            s_full.acquire()
            print(x)
            s_empty.release()


    s_empty = Semaphore(1)
    s_full = Semaphore(0)

    t1 = Thread(target=producer)
    t2 = Thread(target=printer)

    t1.start()
    t2.start()

Upvotes: 1

Related Questions