# Small python program that runs two threads in parallel. # # Thread n's critical section prints (n n n). # # To simulate unpredictable speed of execution, we sleep # random amounts of time before printing (n, n, and n) and # outside the critical section. # # If a (1 1 1) and (2 2 2) are interleaved, then the threads # were both in their critical sections, concurrently. # # If safe is true, we use a mutex semaphore and treat the # printing as a critical section. # from threading import Thread, BoundedSemaphore import random, time # main program creates a couple of threads and runs them. # def main(safe = True, trials = 5): global mutex mutex = BoundedSemaphore(1) p_args = {'safe': safe, 'trials': trials} p1 = Thread(target = thread, args=(1,), kwargs=p_args) p2 = Thread(target = thread, args=(2,), kwargs=p_args) p1.start() p2.start() p1.join() p2.join() print() def thread(pnbr, safe = False, trials = 5): global mutex for i in range(trials): if safe: mutex.acquire() trace(pnbr, '({}') trace(pnbr, '{}') trace(pnbr, '{})') if safe: mutex.release() time.sleep(random.randint(0,2)) def trace(pnbr, tag): print((tag + ' ').format(pnbr), \ end = '', flush = True ) time.sleep(random.randint(0,2))