2014-04-01 27 views
0

我正在測試python線程是如何工作的,我期待的是進程被啓動並完成實時,但它不是我得到的。下面是一個簡單的腳本:Python線程,怪異的結果

import threading 
import time 
import random 


def loop_fn(): 
    for i in range(1, 5): 
     n = random.randint(1,5) 
     print "process", i," started " 
     time.sleep(n) 
     print "process", i," finished" 

threading.Thread(target=loop_fn).start() 
print "end" 

,結果顯示離線多次運行(Windows環境)後:

<1st program run> 
%run threading1.py 
end 
process 1 started 

<2nd program run> 
%run threading1.py 
process 1 finished 
process 2 started 
process 2 finished 
process 3 started 
processend 1 started 

<3rd program run> 
%run threading1.py 
process 3 finished 
process 4 started 
process 4 finished 
endprocess 1 started 

任何提示?

+0

你可能想要的東西,等待做執行 –

回答

1

如果希望進程1到5並行運行,則需要爲每個進程創建一個線程,而不是爲所有五個線程創建一個線程。如果您希望線程在程序終止前完成執行,那麼主線程應該爲每個工作線程join

import threading 
import time 
import random 

def loop_fn(i): 
    n = random.randint(1,5) 
    print "process", i," started " 
    time.sleep(n) 
    print "process", i," finished" 

threads = [] 
for i in range(1, 5): 
    t = threading.Thread(target=loop_fn, args=(i,)) 
    t.start() 
    threads.append(t) 

for t in threads: 
    t.join() 
print "end" 

結果:

process 1 started process 
2 started process 
3process 4 started 
started 
processprocess 32 finished finished 

processprocess 1 finished4 
finished 
end 

或者,您可能需要使用一個Lock進行打印,如果你想更好的輸出。這將防止一個線程開始打印,而另一個線程已完成打印。

import threading 
import time 
import random 

print_lock = threading.Lock() 
def atomic_print(msg): 
    print_lock.acquire() 
    print msg 
    print_lock.release() 


def loop_fn(i): 
    n = random.randint(1,5) 
    atomic_print("process {} started ".format(i)) 
    time.sleep(n) 
    atomic_print("process {} finished".format(i)) 

threads = [] 
for i in range(1,5): 
    t = threading.Thread(target=loop_fn, args=(i,)) 
    t.start() 
    threads.append(t) 

for t in threads: 
    t.join() 
print "end" 

結果:

process 1 started 
process 2 started 
process 3 started 
process 4 started 
process 1 finished 
process 2 finished 
process 4 finished 
process 3 finished 
end 
+0

感謝凱文你的線程,你打在了要害。 – AJN