forked from cskch99/pyspark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread.py
71 lines (56 loc) · 1.74 KB
/
thread.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from pyspark import SparkContext
sc = SparkContext()
import threading
import random
partitions = 5
n = 5000000 * partitions
# use different seeds in different threads and different partitions
# a bit ugly, since mapPartitionsWithIndex takes a function with only index
# and it as parameters
def f1(index, it):
random.seed(index + 987231)
for i in it:
x = random.random() * 2 - 1
y = random.random() * 2 - 1
yield 1 if x ** 2 + y ** 2 < 1 else 0
def f2(index, it):
random.seed(index + 987232)
for i in it:
x = random.random() * 2 - 1
y = random.random() * 2 - 1
yield 1 if x ** 2 + y ** 2 < 1 else 0
def f3(index, it):
random.seed(index + 987233)
for i in it:
x = random.random() * 2 - 1
y = random.random() * 2 - 1
yield 1 if x ** 2 + y ** 2 < 1 else 0
def f4(index, it):
random.seed(index + 987234)
for i in it:
x = random.random() * 2 - 1
y = random.random() * 2 - 1
yield 1 if x ** 2 + y ** 2 < 1 else 0
def f5(index, it):
random.seed(index + 987245)
for i in it:
x = random.random() * 2 - 1
y = random.random() * 2 - 1
yield 1 if x ** 2 + y ** 2 < 1 else 0
f = [f1, f2, f3, f4, f5]
# the function executed in each thread/job
def dojob(i):
count = sc.parallelize(range(1, n + 1), partitions) \
.mapPartitionsWithIndex(f[i]).reduce(lambda a,b: a+b)
print ("Worker", i, "reports: Pi is roughly", 4.0 * count / n)
# create and execute the threads
threads = []
for i in range(5):
t = threading.Thread(target=dojob, args=(i,))
threads += [t]
t.start()
print ("All started!")
# wait for all threads to complete
for t in threads:
t.join()
print ("All done!")