2015-09-17 167 views
0

最近我一直在學習Python的多處理功能和任務的延遲開始遇到問題用下面的代碼與Python多處理

import syslog 
from multiprocessing import Pool 
def launcher(i): 
    time.sleep(i) 
    syslog.openlog('test', 0, syslog.LOG_LOCAL4) 
    syslog.syslog('{} {}'.format(i,datetime.now())) 

if __name__ == '__main__': 
    pool=Pool(8) 
    pool.map(launcher,range(1,3000)) 
    pool.close() 
    pool.join() 

其背後的想法很簡單:我需要得到消息的流動代替在我的系統日誌中(每秒一條消息),但我想用多處理池在8個工作進程中產生它。

在我的系統日誌(其是本地的/ var /日誌/在我的Ubuntu系統日誌),我有以下

Sep 17 17:17:57 test: 1 2015-09-17 17:17:57.225699 
Sep 17 17:17:58 test: 2 2015-09-17 17:17:58.226957 
Sep 17 17:18:00 test: 3 2015-09-17 17:18:00.229196 
Sep 17 17:18:03 test: 4 2015-09-17 17:18:03.232390 
Sep 17 17:18:07 test: 5 2015-09-17 17:18:07.236587 
Sep 17 17:18:12 test: 6 2015-09-17 17:18:12.241737 
Sep 17 17:18:18 test: 7 2015-09-17 17:18:18.247926 
Sep 17 17:18:25 test: 8 2015-09-17 17:18:25.255169 
Sep 17 17:18:29 test: 9 2015-09-17 17:18:29.258229 
Sep 17 17:18:33 test: 10 2015-09-17 17:18:33.263454 
Sep 17 17:18:42 test: 64 2015-09-17 17:18:42.272675 
Sep 17 17:18:52 test: 33 2015-09-17 17:18:52.283012 
Sep 17 17:19:01 test: 11 2015-09-17 17:19:01.290070 
Sep 17 17:19:02 test: 12 2015-09-17 17:19:02.259826 

首先,流程不統一,其次,無序。

如果是這樣,原因是什麼?

爲什麼linux進程調度程序像Python多處理那樣工作?

有什麼辦法解決我的任務多處理?

回答

0

即使OS會做你的程序的實時調度,你不會得到之後每第二個相同的消息:

  1. 採取8個廚房定時器,和後它的堆棧。
  2. 號碼2999 post-its 1 to 2999.
  3. 取一個計時器和一個貼子,並設置時間到貼子上的號碼並將其設置在一邊。
  4. 重複3,直到用完定時器
  5. (如果你非常快,亞秒速度),你有8個定時器從[1,2,3,4,5,6,7,8]
  6. 等待第二
  7. 現在你的第一個計時器應熄滅,重複步驟3
  8. 你現在有8個定時器運行

的順序將是

[9, 1, 2, 3, 4, 5, 6, 7] 
[8, 10, 1, 2, 3, 4, 5, 6] 
[7, 9, 11, 1, 2, 3, 4, 5] 
[6, 8, 10, 12, 1, 2, 3, 4] 
[5, 7, 9, 11, 13, 1, 2, 3] 
[4, 6, 8, 10, 12, 14, 1, 2] 
[3, 5, 7, 9, 11, 13, 15, 1] 
[2, 4, 6, 8, 10, 12, 14, 16] 
#Notice that for the next timer to go off, you have to wait 2 seconds, not 1! 
[17, 2, 4, 6, 8, 10, 12, 14] 
[15, 18, 2, 4, 6, 8, 10, 12] 
... 
[3, 6, 9, 12, 15, 18, 21, 24] 
#3 seconds to wait, not 1! 
[25, 3, 6, 9, 12, 15, 18, 21] 
... 
[4, 8, 12, 16, 20, 24, 28, 32] 

編輯:

我的猜測,爲什麼你經歷瞭如此之快的等待1,2,3可能是因爲你的8名工人同時試圖做IO到相同的系統日誌。我認爲有一些封鎖去那裏。