Quick actions

cmd+k|ctrl+k

Navigation

Languages

evenodd threads semaphore

Snippet info

Language

Python

Visibility

public

Author

arthurpc02

Created

2026-06-04T22:43:02.342041Z

Updated

2026-06-04T23:21:20.146834Z

import threading


class odd_thread(threading.Thread):
    def __init__(self, thread_name, thread_ID):
        threading.Thread.__init__(self)
        self.thread_name = thread_name 
        self.thread_ID = thread_ID


    def run(self):
        global counter
        while(counter < 20):
            odd_sem.acquire()
            print(f"odd: {counter}")
            counter+=1;
            even_sem.release()
                    
                    
class even_thread(threading.Thread):
    def __init__(self, thread_name, thread_ID):
        threading.Thread.__init__(self)
        self.thread_name = thread_name 
        self.thread_ID = thread_ID


    def run(self):
        global counter
        while(counter < 20):
            even_sem.acquire()
            print(f"even: {counter}")
            counter+=1;
            odd_sem.release()


print("Hello World!")

counter = 1
counter_mutex = threading.Lock()
odd_sem = threading.Semaphore(1)
even_sem = threading.Semaphore(0)

thread_odd = odd_thread("odd", 1)
thread_even = even_thread("even", 2)

thread_odd.start()
thread_even.start()

thread_odd.join()
thread_even.join()

print("Good bye world")
INFO