Codes for Binary and Counting Semaphores for GFG

Just finished 2 codes, of semaphores in C and Python, although C was a real headache, what a pain it is to code in C, although I like the way the language is close to the machine but still can't tolerate more than half hour of coding in it.

Then the Python code was really interesting, it just simply shows and will be very easy for anyone, anyone, to understand and comprehend, well, this is what I think.... 

For the day, I think it was fairly fruitful but nowadays I just want more and more productivity from my days, I'm working on it, working on myself, although if I remember last year at this time, I usually had like 2 to 3 priorities for they whole day without the college shit but nowadays in the same conditions these have increased to total of 7 priorities in different levels.

I got the mail for the Publishing of my 2 Codes on GFG and I was thinking of also submitting a C code for that article cause the code they had was really trash, but then dropped the idea for today cause I have to hit the bed early today.

Using C after a long time ;)


Well, that's it for today and the Python code for Counting Semaphores is provided below;

import heapq
# Global Variable to track the Processes going into Critical Section
COUNTER=1

class Semaphore:
    def __init__(self,value):
        # Value of the Semaphore passed to the Constructor
        self.value=value
        # The Waiting queue which will be using the heapq module of Python
        self.q=list()

    def getSemaphore(self):
        ''' Function to print the Value of the Semaphore Variable '''
        print(f"Semaphore Value: {self.value}")
       
def block(process):
    print(f"Process {process} Blocked.")
   
def wakeup(process):
    print(f"Process {process} Waked Up and Completed it's work.")

def P(s):
    global COUNTER
    s.value=s.value-1
    if(s.value<0):
        heapq.heappush(s.q,COUNTER)
        block(COUNTER)
    else:
        print(f'Process {COUNTER} gone inside the Critical Section.')
        COUNTER+=1
        return
   
def V(s):
    global COUNTER
    s.value=s.value+1
    if(s.value<=0):
        p=heapq.heappop(s.q)
        wakeup(p)
        COUNTER-=1
    else:
        print(f"Process {COUNTER} completed it's work.")
        COUNTER-=1
        return
   
# Can Pass the Value of the Counting Semaphore to the Class Constructor

# Example for Counting Semaphore value as 2
s1=Semaphore(2)
s1.getSemaphore()

P(s1)
s1.getSemaphore()

P(s1)
s1.getSemaphore()

P(s1)
s1.getSemaphore()

V(s1)
s1.getSemaphore()

V(s1)
s1.getSemaphore()

V(s1)
s1.getSemaphore()

# This Code is Contributed by Himesh Singh Chauhan

Comments

Popular Posts