關於multiprocessing,我也來聊幾句,multiprocessing
起因:最近需要從hbase中向 ES中導一批資料,使用multiprocessing 啟動多個程式同時向ES導資料,可以大大提高效率,因為導數的任務是可以按照時間分割的。
一段簡單的代碼如下:
from multiprocessing import Pooldef f(x): return x*xif __name__ == '__main__': pool = Pool(processes=4) # start 4 worker processes result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously print result.get(timeout=1) # prints "100" unless your computer is *very* slow print pool.map(f, range(10))
令我十分不解的,multiprocessing 是如何?任務的分發,以及結果的回傳的。我希望能夠把它的實現機制與作業系統的進程機制對應起來。
經過閱讀代碼,得出的結論如下:
1. 父進程作為整個任務的分發器,每個worker是一個子進程
2. 子進程和父進程之間通過管道通訊,包括任務的分發和結果的回傳(2個【管道】) ,管道通過【訊號量】加鎖
下面羅列部分核心代碼,加入我自己的注釋,方便大家閱讀代碼時參考:
1. 管道的建立
def _setup_queues(self): from .queues import SimpleQueue self._inqueue = SimpleQueue() # 管道1 用於分發任務 self._outqueue = SimpleQueue() # 管道2 用於推送結果 self._quick_put = self._inqueue._writer.send self._quick_get = self._outqueue._reader.recv
再查看 SimpleQueue
class SimpleQueue(object): def __init__(self): self._reader, self._writer = Pipe(duplex=False) self._rlock = Lock() if sys.platform == 'win32': self._wlock = None else: self._wlock = Lock() self._make_methods()
在查看 Pipe
def Pipe(duplex=True): ''' Returns two connection object connected by a pipe ''' from multiprocessing.connection import Pipe return Pipe(duplex)
if sys.platform != 'win32': def Pipe(duplex=True): # duplex 是否是全雙工系統 ''' Returns pair of connection objects at either end of a pipe ''' if duplex: s1, s2 = socket.socketpair() s1.setblocking(True) s2.setblocking(True) c1 = _multiprocessing.Connection(os.dup(s1.fileno())) c2 = _multiprocessing.Connection(os.dup(s2.fileno())) s1.close() s2.close() else: fd1, fd2 = os.pipe() c1 = _multiprocessing.Connection(fd1, writable=False) c2 = _multiprocessing.Connection(fd2, readable=False) return c1, c2
非常用意思的是,如果是全雙工系統的話,直接用socket 來實現
SimpleQueue 是加過鎖的,可以用於多進程間並發讀寫,來看看鎖的實現
class Lock(SemLock): # 到這裡python 代碼已經無法再跳入,SemLock 引自 _multiprocessing.so def __init__(self): SemLock.__init__(self, SEMAPHORE, 1, 1
由SemLock 可以推斷,鎖就是通過訊號量實現的。
2. worker的建立
def _repopulate_pool(self): """Bring the number of pool processes up to the specified number, for use after reaping workers which have exited. """ for i in range(self._processes - len(self._pool)): w = self.Process(target=worker, args=(self._inqueue, self._outqueue, # 管道作為參數被傳入 self._initializer, self._initargs, self._maxtasksperchild) ) self._pool.append(w) w.name = w.name.replace('Process', 'PoolWorker') w.daemon = True w.start() debug('added worker')
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None): assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) put = outqueue.put # ***留意這裡*** get = inqueue.get # ***留意這裡***# 省略部分代碼 completed = 0 while maxtasks is None or (maxtasks and completed < maxtasks): try: task = get() # ***留意這裡*** 任務是子進程自己從【管道】中取回的,這裡的管道相當於訊息佇列了 except (EOFError, IOError): debug('worker got EOFError or IOError -- exiting') break if task is None: # 如果任務是None worker就退出了 debug('worker got sentinel -- exiting') break job, i, func, args, kwds = task try: result = (True, func(*args, **kwds)) except Exception, e: result = (False, e) try: put((job, i, result)) # ***留意這裡*** 結果推回隊列 except Exception as e: wrapped = MaybeEncodingError(e, result[1]) debug("Possible encoding error while sending result: %s" % ( wrapped)) put((job, i, (False, wrapped))) completed += 1 debug('worker exiting after %d tasks' % completed
明白了這些對於multiprocessing 的使用,我明顯就有了底氣
mann是中國防水防摔的手機沒錯,就品質上來說確實很牛逼,但是大家不可以忘了諾基亞機皇時代了吧,那個
看你寫了這麼多,我也來聊幾句。諾基亞不是輸在品質,而是輸在轉型太慢,定位不準確,沒有選好陣營,這點導致節節失敗。
怎才可以跟新認識的朋友或網友開心的聊天,怎我發現我跟人聊天,聊來聊去就那幾句沒營養的話?該怎做
真誠的和新認識的朋友聊天,瞭解一下他的簡單情況,切記不要刨根問底,交朋友重在交心。