2013-07-30 78 views
2

此代碼不會給我我期望的輸出。有些事情一定是錯的,但我不明白它會是什麼。爲什麼第二個線程不能啓動?

import thread 
import time 

def func1(threadName, sleepTime): 
    while 1 < 2: 
     time.sleep(sleepTime) 
     print "%s" % (threadName) 

def func2(threadName, sleepTime): 
    while 1 < 2: 
     time.sleep(sleepTime) 
     print "%s" % (threadName) 


try: 
    thread.start_new_thread(func1("slow" , 5)) 
    thread.start_new_thread(func2("fast" , 1)) 
except Exception, e: 
    print str(e) 

我期望的輸出是一樣的東西:

fast 
fast 
fast 
fast 
slow 
fast 

等,但只有第一個線程似乎開始。之後我實現了「try and except」塊,以查看是否有錯誤,但沒有錯誤!

+1

看起來好像函數在線程啓動之前被調用。 – Brilliand

+0

花時間格式化和拼寫檢查您的問題。如果你沒有對你的問題做任何努力,你怎麼能期望我們付出努力來回答它? – dimo414

回答

6

看起來好像函數在線程啓動之前被調用。我不是很熟悉Python,但嘗試:

thread.start_new_thread(func1, ("slow" , 5)) 
thread.start_new_thread(func2, ("fast" , 1)) 

注意函數名後的逗號 - 你在函數傳遞作爲一個參數,並作爲單獨的參數參數參數的元組。當新線程準備好時,這讓start_new_thread可以調用你的函數。

+0

是的,非常感謝你!我,有時會失明;) – PhilliPy

+0

這正是發生了什麼事情。 –

相關問題