how to multithread a function in python code example
Example 1: multithreading in python
from multiprocessing.pool import ThreadPool
def stringFunction(value):
my_str = 3 + value
return my_str
def stringFunctio(value):
my_str = 33 + value
return my_str
pool = ThreadPool(processes=1)
thread1 = pool.apply_async(stringFunction,(8,))
thread2 = pool.apply_async(stringFunctio,(8,))
return_val = thread1.get()
return_val1 = thread2.get()
Example 2: multithread python3
import timeimport threadingdef calc_square(number): print("Calculate square numbers: ") for i in numbers: time.sleep(0.2) #artificial time-delay print('square: ', str(n*n))def calc_cude(number): print("Calculate cude numbers: ") for i in numbers: time.sleep(0.2) print('cube: ', str(n*n*n))arr = [2,3,8,9]t = time.time()t1 = threading.Thread(target = cal_square,args=(arr,))t2 = threading.Thread(target = cal_cube,args=(arr,))# creating two threads here t1 & t2t1.start()t2.start()# starting threads here parallelly by usign start function.t1.join()# this join() will wait until the cal_square() function is finised.t2.join()# this join() will wait unit the cal_cube() function is finised.print("Successed!")