Search⌘ K
AI Features

Solution: Create Random Number and Print a Square and a Cube via Threads

Explore how to use Python threading to create three coordinated threads that generate random numbers and print their squares and cubes. Understand synchronization methods such as locks and condition variables to manage inter-thread communication and ensure proper execution order.

We'll cover the following...

The solution to the problem of writing a program in which the first thread produces random numbers, the second thread prints the square of the number, and the third thread prints the cube of the random number is below.

Solution

Python 3.8
import threading
import random
import queue
import time
import collections
def generate( ) :
for i in range(10) :
cond.acquire( )
num = random.randrange(10, 20)
print('Generated number =', num)
qfors.append(num)
qforc.append(num)
cond.notifyAll( )
cond.release( )
def square( ) :
for i in range(10) :
cond.acquire( )
if len(qfors) :
num = qfors.popleft( )
print('num =', num, 'Square =', num * num)
cond.notifyAll( )
cond.release( )
def cube( ) :
for i in range(10) :
cond.acquire( )
if len(qforc) :
num = qforc.popleft( )
print('num =', num, 'Cube =', num * num * num)
cond.notifyAll( )
cond.release( )
qfors = collections.deque( )
qforc = collections.deque( )
cond = threading.Condition( )
th1 = threading.Thread(target = generate)
th2 = threading.Thread(target = square)
th3 = threading.Thread(target = cube)
th1.start( )
th2.start( )
th3.start( )
th1.join ( )
th2.join( )
th3.join( )
print('All Done!!')

Explanation

...