簡體   English   中英

使用thread.start_new_thread()在Python 2.6中進行簡單線程化

[英]Simple threading in Python 2.6 using thread.start_new_thread()

我正在關注有關簡單線程的教程。 他們給出了這個例子,當我嘗試使用它時,我從解釋器中收到了難以理解的錯誤。 您能告訴我為什么這不起作用嗎? 我在使用Python 2.6的WinXP SP3上

import thread

def myfunction(mystring,*args):
    print mystring


if __name__ == '__main__':

    try:

        thread.start_new_thread(myfunction,('MyStringHere',1))

    except Exception as errtxt:
        print errtxt

執行此操作將導致:

sys.excepthook中的Error啟動的線程中未處理的異常:

最初的例外是:

錯誤中丟失的信息實際上在輸出中丟失。

問題在於您的主線程在新線程有時間完成之前已經退出。 解決方案是在主線程上等待。

import thread, time

def myfunction(mystring,*args):
    print mystring


if __name__ == '__main__':

    try:

        thread.start_new_thread(myfunction,('MyStringHere',1))

    except Exception, errtxt:
        print errtxt

    time.sleep(5)

附帶說明,您可能要使用線程模塊。 您的主線程將在退出之前等待所有這些類型的線程關閉:

from threading import Thread

def myfunction(mystring,*args):
    print mystring


if __name__ == '__main__':

    try:
        Thread(target=myfunction, args=('MyStringHere',1)).start()
    except Exception, errtxt:
        print errtxt

您需要等待Thread完成其工作,因此您必須使用Thread.join():

from threading import Thread

def myfunction(mystring,*args):
    print mystring

if __name__ == '__main__':

    try:
        t = Thread(None,myfunction,None,('MyStringHere',1))
        t.start()
        t.join()
    except Exception as errtxt:
        print errtxt
import thread

def myfunction(mystring,*args):
    print mystring

if __name__ == '__main__':

    try:

        thread.start_new_thread(myfunction,('MyStringHere',1))

    except Exception as errtxt:
        print errtxt

while 1:
    pass

最后放置while循環,然后它將為您工作。

更改后,我在Mac上的Python 2.5中進行了嘗試

except Exception as errtxt:

except Exception, errtxt:

該程序未引發異常,但也未打印任何內容。 不確定是否有幫助,但我確實感到好奇...

當我在Python 2.6中運行此代碼時,它起作用了,是否可能已經有鎖定該函數的開放線程? 我建議完全關閉Python,檢查您正在運行的進程以確保您的進程沒有任何運行,然后重試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM