Answers for "# multithreading for optimal use of CPU"

0

# multithreading for optimal use of CPU

# multithreading for optimal use of CPU
import time
import threading

def calc_square(numbers):
    print("calculate square numbers")
    for n in numbers:
        time.sleep(1) # CPU becomes idle for 1 second
        print('square:',n*n)

def calc_cube(numbers):
    print("calculate cube of numbers ")
    for n in numbers:
        time.sleep(1) # CPU becomes idle for 1 second
        print('cube:',n*n*n)

arr = [2,3,8,9]

t = time.time()

t1= threading.Thread(target=calc_square, args=(arr,))
t2= threading.Thread(target=calc_cube, args=(arr,))

t1.start()
t2.start()

t1.join()
t2.join()

print("DONE IN : ",time.time()-t)

# Multithreading allows the execution of multiple parts of a program at the same time. This can be crucial at times when multiple actions that happen simultaneously needs to be handled. Else, they can be used to execute another piece of code(function) while the CPU is idle.
Posted by: Guest on March-27-2022

Python Answers by Framework

Browse Popular Code Answers by Language