2014-01-15 39 views
0

我已經寫了線程非常基本的Python代碼...線程在python面臨麻煩

import time 
import thread 

def print_hello(name,delay): 
    while 1: 
     print name 
     time.sleep(delay) 

     try: 
      thread.start_new_thread(print_hello, ("frist",1,)) 
      thread.start_new_thread(print_hello, ("second",2,)) 
     except: 
      print "unable to start thread" 

     time.sleep(4) 
     print "hello" 

其輸出是:

second 
frist 
frist 
second 
frist 
frist 
hello 

例外:

Unhandled exception in thread started by 
    sys.excepthook is missing 
    lost sys.stderr 

Unhandled exception in thread started by 
    sys.excepthook is missing 
    lost sys.stderr 

我的查詢:

  1. 爲何再來第一名?
  2. 爲什麼異常?
+3

有些人在遇到問題時會想「我會用線程」。然後他們有兩個具有錯誤。 –

回答

1

這是一個無限循環。

print_hello功能開始啓動其它啓動一個線程線程線程...

不好的事情會發生,並最終將崩潰。

3

簡單的回答:因爲線程是棘手的。

零度,上面輸入的代碼不可能產生您顯示的輸出。我認爲你的真正意圖是從try:下來的所有東西都被壓縮到與def相同的水平。當我做出這一改變,並運行你的代碼時,我會得到類似於你的結果,有時

爲了解決您的第一個問題:Frist第二個來,因爲time.sleep()不能保證它會延遲準確的指定時間。請參閱文檔here。 當我運行你的代碼時,有時候第一個出現,有時第一個出現,有時它們一起出現。

解決你的第二個問題:因爲當主程序退出時,你的兩個後臺線程會從他們的下面拉出地毯。

當主程序執行sleepprint時,兩個線程運行正常。一旦這些完成,程序嘗試退出。幾乎在同一時間,兩個線程正試圖打印他們的輸出。

我發現,如果增加sleep(4)sleep(5.5)運行會更加清晰,因爲兩個線程試圖print當程序退出。

在現實生活中,你應該做的是有一個機制來指示後臺線程脫離他們的無限循環並在主程序退出之前退出,然後讓主程序等待(通過調用join()),直到線程有在退出之前停止。

閱讀關於threadingjoin

+0

你好,我是threading程序新手。我在這裏得到了重點,但我也有一些基本的查詢如何線程實際工作?是所有的分配給一個單獨的堆棧,我很驚訝爲什麼線程停止一旦程序執行停止。 – user2743375

+0

@ user2743375我對內部細節瞭解不多。也許這個問題(http://stackoverflow.com/questions/31340/how-do-threads-work-in-python-and-what-are-common-python-threading-specific-pit)將有所幫助。 – jwygralak67

+0

+1,用於「頭」的一致使用:D –