總算把程式碼弄了一個段落,還是想要破解之前一直搞不懂的 threading 多線程物件到底要怎麼用,剛好看到 youtube 的教學 " 学会多线程 python threading教学 学习教程 "
教學簡單明瞭,但是我個人覺得在概念與整體架構的介紹詳細程度上不是很完善,主打快速上使用吧,總之我是看了XD,然後自己練習了一下。
其實有範例 Code 之後就懂很快,也可以把基本的 Thread 物件與 Lock物件兜出來,了卻一樁小小心願這樣XD
Code 如下:
教學簡單明瞭,但是我個人覺得在概念與整體架構的介紹詳細程度上不是很完善,主打快速上使用吧,總之我是看了XD,然後自己練習了一下。
其實有範例 Code 之後就懂很快,也可以把基本的 Thread 物件與 Lock物件兜出來,了卻一樁小小心願這樣XD
Code 如下:
import threading #導入 threading 模組
from multiprocessing import Queue #使用多核心的模組 Queue
#定義第一個線程工作
#num是給 job1 吃的參數,q是 Queue物件,而 lock 是線程鎖。
def job1(num, q, lock):
lock.acquire() #鎖上這個線程,在完成之前不讓其他線程對變數做干擾。
sum = 0
for i in range(num):
sum += i
q.put(sum) #把算出來的答案放入 Queue 中,後續再取出。
lock.release() #解鎖這個線程,開始其他線程。
#Thread 裡面的 function 不可以有 return, 不然會出錯。
#定義第二個線程工作
def job2(num, q, lock):
lock.acquire()
sum = 0
for i in range(num):
sum += i**10
q.put(sum)
lock.release()
#定義主程式
def main():
lock = threading.Lock() #命名一個 Lock 物件
q = Queue() # 開一個 Queue 物件
t1 = threading.Thread(target=job1, args=(8,q,lock))
#打開一個名字叫 t1 的線程物件
#這個物件會去呼叫 job1
#同時t1導入 q 跟 lock 做現成控制
#為什麼要這樣做...我也不知道XD
t2 = threading.Thread(target=job2, args=(8,q,lock))
t1.start() #啟動 t1 線程
t2.start() #啟動 t2 線程
t1.join() #在 t1線程結束前阻止程式繼續運行
t2.join() #在 t2線程結束前阻止程式繼續運行
#確認Queue是否為空,如果不是就用 q.get() 取出值
while not q.empty():
print(q.get())
print "END Section!"
if __name__ == '__main__': main()
簡單的小範例~挺好兜的,不過真的的功能應該還要再把文件好好看過才是="=
# 6/20更新: 另外列出在stackoverflow上面別人列出 multiprocess 跟 multithread 的優劣評比,參考一下。
Multiprocessing
Pros
- Separate memory space
- Code is usually straightforward
- Takes advantage of multiple CPUs & cores
- Avoids GIL limitations for cPython
- Eliminates most needs for synchronization primitives unless if you use shared memory (instead, it's more of a communication model for IPC)
- Child processes are interruptible/killable
- Python
multiprocessingmodule includes useful abstractions with an interface much likethreading.Thread - A must with cPython for CPU-bound processing
Cons
- IPC a little more complicated with more overhead (communication model vs. shared memory/objects)
- Larger memory footprint
Threading
Pros
- Lightweight - low memory footprint
- Shared memory - makes access to state from another context easier
- Allows you to easily make responsive UIs
- cPython C extension modules that properly release the GIL will run in parallel
- Great option for I/O-bound applications
Cons
- cPython - subject to the GIL
- Not interruptible/killable
- If not following a command queue/message pump model (using the
Queuemodule), then manual use of synchronization primitives become a necessity (decisions are needed for the granularity of locking) - Code is usually harder to understand and to get right - the potential for race conditions increases dramatically
留言
張貼留言