Simple usage of Threads with Python

We define a costly function that will be called from different ththreads :


In [1]:
K = 50
 
def CostlyFunction(z):
	result = 0
	for k in range(1, K+2):
		result += z ** (1 / k**1.5)
	return result

In [2]:
import threading
 
K = 50
 
class CostlyThread(threading.Thread):
 
	def __init__(self, value):
 
		threading.Thread.__init__(self)
		self.value = value
 
	def run(self):
		# notre fonction
		result = 0
		z = self.value
		for k in range(1, K+2):
			result += z ** (1 / k**1.5)
		self.value = result

In [3]:
import time
 
# timer
startTime = time.time()
 
# va stocker les threads qu'on va lancer.
threadList = []
 
for i in range(100000) :	# on lance cent milles threads
 
	curThread = CostlyThread(i)
	curThread.start()	# on lance le thread
	threadList.append(curThread)	# on ajoute le thread a la list
 
# maintenant qu'on a tout lance, on récupère tout!
resultList = []
 
for curThread in threadList :
 
	curThread.join()	# on attend que le thread ait fini
	result = curThread.value	# on récupère sa valeur
	resultList.append(result)
 
print(time.time() - startTime)


10.021436214447021

In [4]:
import multiprocessing as mp
 
# timer
startTime = time.time()
 
pool = mp.Pool()
asyncResult = pool.map_async(CostlyFunction, range(100000))	# on lance aussi cent milles operations
pool.close()
pool.join()
resultList = asyncResult.get()	# asyncResult.get() is a list of values
print(time.time() - startTime)


2.3470499515533447

In [ ]: