Wednesday, August 9, 2023

Q4)Write a Python multithreading program which creates two threads, one for calculating the square of a given number and other for calculating the cube of a given number.

import threading

 

def calculate_square(number):

    square = number * number

    print(f"Square of {number} is {square}")

 

def calculate_cube(number):

    cube = number * number * number

    print(f"Cube of {number} is {cube}")

 

def main():

    number = int(input("Enter a number: "))

   

    thread_square = threading.Thread(target=calculate_square, args=(number,))

    thread_cube = threading.Thread(target=calculate_cube, args=(number,))

   

    thread_square.start()

    thread_cube.start()

   

    thread_square.join()

    thread_cube.join()

   

    print("Both threads have finished")

 

if __name__ == "__main__":

    main()

No comments:

Post a Comment