Skip to content

Commit

Permalink
improved the code
Browse files Browse the repository at this point in the history
  • Loading branch information
sherAfzal861 committed Sep 19, 2024
1 parent 2906e89 commit 7bc3c05
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions operating_system/process_synchronization/semaphore.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from random import random
from threading import Event, Thread, current_thread
from time import sleep

Expand Down Expand Up @@ -57,6 +56,11 @@ class ThreadManager:
Thread 1 is working with the resource.
Thread-2 (thread_task) has acquired a resource.
Thread 2 is working with the resource.
>>> sleep(4)
Thread 1 has finished and is releasing the resource.
A resource has been released.
Thread 2 has finished and is releasing the resource.
A resource has been released.
"""

def __init__(self, semaphore: CustomSemaphore, thread_count: int) -> None:
Expand All @@ -74,7 +78,7 @@ def thread_task(self, thread_id: int) -> None:
thread_name = current_thread().name
self.semaphore.acquire(event, thread_name)
print(f"Thread {thread_id} is working with the resource.")
sleep(2 + random()) # Simulate some work
sleep(2) # Simulate some work
print(f"Thread {thread_id} has finished and is releasing the resource.")
self.semaphore.release()

Expand Down

0 comments on commit 7bc3c05

Please sign in to comment.