...

/

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

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

Learn how to write 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.

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

Press + to interact
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

...