41. from threading import Thread
start??
def do_work(start, end, result):
sum = 0 end??
for i in range(start, end): ???
sum += i
result.append(sum)
return ???
if __name__ == "__main__":
2??
START, END = 0, 20000000 ????.
result = list()
th1 = Thread(target=do_work, args=(START, END/2, result))
th2 = Thread(target=do_work, args=(END/2, END, result))
th1.start()
th2.start()
th1.join()
th2.join()
print "Result : ", sum(result)
42. ??? 1? ??? 2?
$ time python 1thread.py $ time python 2thread.py
Result : 199999990000000 Result : 199999990000000
real 0m3.523s real 0m4.225s
?-_-?
61. CPU READ/WRITE
????? I/O? ???? Python ???? ??!
C
P READ/WRITE
U
??? ??
?? ??????
??? I/O bound!!
? C
? P READ/WRITE
? U
??? ???~!
C
??? P READ/WRITE
U
66. from multiprocessing import Process, Queue
def do_work(start, end, result):
sum = 0
for i in range(start, end):
sum += i
result.put(sum)
return
if __name__ == "__main__":
START, END = 0, 20000000
result = Queue()
pr1 = Process(target=do_work, args=(START, END/2, result))
pr2 = Process(target=do_work, args=(END/2, END, result))
pr1.start()
pr2.start()
pr1.join()
pr2.join()
result.put('STOP')
sum = 0
while True:
tmp = result.get()
if tmp == 'STOP': break
else: sum += tmp
print "Result : ", sum
67. ??? 2? ???? 2?
$ time python 2thread.py $ time python 2process.py
Result : 199999990000000 Result : 199999990000000
real 0m4.225s real 0m1.880s
??!
????(sec)
4.2
1.8
2 thread 2 process