Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/algorithm_pyex_multiprocessing.py
1240 views
1
import time
2
from multiprocessing import Process, Queue
3
4
def factorial(queue, N):
5
"Compute a factorial."
6
# If N is a multiple of 4, this function will take much longer.
7
if (N % 4) == 0:
8
time.sleep(0.05 * N/4)
9
10
# Calculate the result
11
fact = 1
12
for i in range(1, N+1):
13
fact = fact * i
14
15
# Put the result back into the Queue
16
queue.put(fact)
17
18
if __name__ == '__main__':
19
queue = Queue()
20
21
N = 5
22
23
p = Process(target=factorial, args=(queue, N))
24
p.start()
25
p.join()
26
27
result = queue.get()
28
29
print('Factorial', N, '=', result)
30
31