2017-03-06 50 views
0

看起來多線程之間的多處理交換更快,所以我開始研究交換,但我得到了一些意想不到的結果。當一個線程沒有在之前,它會導致我的整個腳本循環幾次。導致整個腳本循環的Python多重處理

片段例如:

stuff_needs_done = true 
more_stuff_needs_done = true 
print "Doing stuff" 

def ThreadStuff(): 
    while 1 == 1: 
    #do stuff here 

def OtherThreadStuff(): 
    while 1 == 1: 
    #do other stuff here 

if stuff_needs_done == true: 
    Thread(target=ThreadStuff).start() 

if more_stuff_needs_done == true: 
    Thread(target=OtherThreadStuff).start() 

這個工程,我所期待。線程開始並運行直到停止。但是,當運行很多這些開銷更高(所以我被告知),所以我嘗試交換到多處理。

片段例如:

stuff_needs_done = true 
more_stuff_needs_done = true 
print "Doing stuff" 


def ThreadStuff(): 
    while 1 == 1: 
    #do stuff here 

def OtherThreadStuff(): 
    while 1 == 1: 
    #do other stuff here 

if stuff_needs_done == true: 
    stuffproc1= Process(target=ThreadStuff).start() 

if more_stuff_needs_done == true: 
    stuffproc1= Process(target=OtherThreadStuff).start() 

但是似乎發生是整個事情開始幾次,所以「做的東西」輸出來了一對夫婦線程的運行。

我可以放入一些.join()s,但沒有應該導致打印輸出再次運行的循環,這意味着無處等待。

我的希望是這只是一個語法的東西,但我很難找出爲什麼整個腳本循環。我真的很感謝任何正確的方向。

+0

你有一個語法錯誤幾乎每一行。請[編輯]您的文章以糾正它們。 –

回答

1

這在docs中提到:

Safe importing of main module

Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process).

For example, under Windows running the following module would fail with a RuntimeError:

from multiprocessing import Process 

def foo(): 
    print 'hello' 

p = Process(target=foo) 
p.start() 

Instead one should protect the 「entry point」 of the program by using if __name__ == '__main__' : as follows:

from multiprocessing import Process, freeze_support 

def foo(): 
    print 'hello' 

if __name__ == '__main__': 
    freeze_support() 
    p = Process(target=foo) 
    p.start() 

This allows the newly spawned Python interpreter to safely import the module and then run the module’s foo() function.

+0

完美謝謝! – PoweredByCoffee