所以我想創建一個使用python多處理模塊的進程,我希望它是更大腳本的一部分。 (我也想了很多其他的東西,從它,但現在我會滿足於這一點)多處理代碼重複運行
我從multiprocessing docs複製最基本的代碼,並修改了它稍微
然而,一切外if __name__ == '__main__':
的每次調用p.join()時,語句都會重複重複。
這是我代碼:
from multiprocessing import Process
data = 'The Data'
print(data)
# worker function definition
def f(p_num):
print('Doing Process: {}'.format(p_num))
print('start of name == main ')
if __name__ == '__main__':
print('Creating process')
p = Process(target=f, args=(data,))
print('Process made')
p.start()
print('process started')
p.join()
print('process joined')
print('script finished')
這是我預期:
The Data
start of name == main
Creating process
Process made
process started
Doing Process: The Data
process joined
script finished
Process finished with exit code 0
這是現實:
The Data
start of name == main
Creating process
Process made
process started
The Data <- wrongly repeated line
start of name == main <- wrongly repeated line
script finished <- wrongly executed early line
Doing Process: The Data
process joined
script finished
Process finished with exit code 0
我不確定這是否是由if
聲明或p.join()
或其他內容引起的,並且是由爲什麼會發生這種情況。有人可以解釋一下是什麼引起這個和爲什麼?
爲了清楚起見,因爲有些人不能複製我的問題,但我有;我正在使用Windows Server 2012 R2 Datacenter,我正在使用python 3.5.3。
使用多處理模塊時,會創建一個全新的python進程,這意味着python腳本基本上是重複的。唯一的區別是新創建的進程會有一個目標方法,並且該目標是執行的目標。任何函數定義之外的所有代碼都以與任何python腳本行爲相同的方式運行。這是我的理解。 – Peter
無法重現您的結果。代碼在我的機器上工作正常,也http://www.tutorialspoint.com/execute_python_online.php?PID=0Bw_CjBb95KQMVFJETFNzZG1rX1U – aristotll
@aristotll我不能exaplain爲什麼它在網上工作,但我已經在兩臺計算機上運行這裏,它每次都失敗 - 但無論如何,謝謝檢查。 –