Search⌘ K
AI Features

... continued

Explore how to use Python's threading module to manage communication between threads using condition variables. Understand synchronization techniques by implementing a prime number printer program where finder and printer threads coordinate printing primes safely and efficiently.

We'll cover the following...

Let's rewrite our printer thread first using the correct condition variable pattern. The first task the printer does is to wait for a prime number to become available. We can achieve that using the following snippet:

Printer thread waiting

        cond_var.acquire()
        while not found_prime and not exit_prog:
            cond_var.wait()
        cond_var.release()

Once the printer thread has printed the found prime number, it needs to let the finder thread know to continue finding the next prime number. To achieve that we'll notify the condition variable after printing the prime number. In the finder thread code, we'll make the finder thread wait on the condition variable. The complete code for the printer thread appears below:

Printer thread
def printer_thread():
    global prime_holder
    global found_prime

    while not exit_prog:

        # wait for a prime number to become
        # available for printing
        cond_var.acquire()
        while not found_prime and not exit_prog:
            cond_var.wait()
        cond_var.release()

        if not exit_prog:
            # print the prime number
            print(prime_holder)

            # reset. We can skip this statement if we like
            prime_holder = None

            # make sure to wake up the finder thread
            cond_var.acquire()
            found_prime = False
            cond_var.notify()
            cond_var.release()

...