-
Notifications
You must be signed in to change notification settings - Fork 0
/
Threading.py
134 lines (111 loc) · 2.47 KB
/
Threading.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import threading
from threading import Thread
import time, random, Queue
def doubler(number):
print(threading.currentThread().getName())
print(number * 2)
print('\n')
jack = 0
jill = 100
def inc():
global counter
counter += 1
def dec():
global counter
counter -= 1
def give_to_jack():
global jack, jill
time.sleep(random.random())
if jill > 0:
jill -= 1
jack += 1
def give_to_jill():
global jack, jill
time.sleep(random.random())
if jack > 0:
jack -= 1
jill += 1
def funnel_to_jack():
while jill > 0:
give_to_jack()
def funnel_to_jill():
while jack > 0:
give_to_jill
# if __name__ == '__main__':
# for _ in range(10):
# # time.sleep(random.random())
# threading.Thread(target=funnel_to_jack).start()
# threading.Thread(target=funnel_to_jill).start()
def summ(L):
if L == []:
return 0
elif len(L) == 1:
return L[0]
else:
time.sleep(1)
return summ(L[:len(L)/2]) + summ(L[len(L)/2:])
def sumt(L):
if L == []:
return 0
elif len(L) == 1:
return L[0]
else:
time.sleep(1)
q = Queue.Queue()
left = Thread(target=lambda q, M: q.put(sumt(M)), args=(q, L[:len(L)/2]))
right = Thread(target=lambda q, M: q.put(sumt(M)), args=(q, L[len(L)/2:]))
left.start()
right.start()
left.join()
right.join()
return q.get() + q.get()
if __name__ == '__main__':
L = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
t0 = time.time()
print summ(L), time.time()-t0
t1 = time.time()
print sumt(L), time.time()-t1
# from threading import Thread
# from multiprocessing import Pool
# import time
#
# def show(x):
# print x
#
# def show_n(x, n):
# for _ in range(n):
# time.sleep(.1)
# print x
#
# def show_50(x):
# show_n(x, 50)
#
# def show_forever(x):
# while True:
# print x
#
# def re(x):
# return x
#
# counter = 0
#
# def increment_n(counter,n):
# for _ in range(n):
# time.sleep(.1)
# counter += 1
# print counter
#
# def decrement_n(counter,n):
# for _ in range(n):
# time.sleep(.1)
# counter -= 1
# print counter
#
# pool = Pool(2)
# thing = pool.map(show_50, ["hello", "goodbye"])
# thing
# hello = Thread(target=increment_n, args=(counter,50))
# goodbye = Thread(target=decrement_n, args=(counter,50))
#
# hello.start()
# goodbye.start()