13 python multithreading python-2.6
我正在学习关于简单线程的教程.他们给出了这个例子,当我尝试使用它时,我从解释器中得到了难以理解的错误.你能告诉我为什么这不起作用吗?我正在使用WinXP SP3和Python 2.6当前版本
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
Run Code Online (Sandbox Code Playgroud)
执行此结果::
在sys.excepthook中由Error启动的线程中未处理的异常:
最初的例外是:
输出中实际上缺少错误中缺少的信息.
Unk*_*own 25
问题是你的主线程在新线程有时间完成之前已经退出.解决方案是在主线程上等待.
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)
Run Code Online (Sandbox Code Playgroud)
另外,您可能希望使用线程模块.您的主线程将在退出之前等待所有这些类型的线程关闭:
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
Run Code Online (Sandbox Code Playgroud)
ism*_*ail 16
您需要等到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
Run Code Online (Sandbox Code Playgroud)
我在Mac上的Python 2.5中尝试过,更改后
except Exception as errtxt:
Run Code Online (Sandbox Code Playgroud)
到
except Exception, errtxt:
Run Code Online (Sandbox Code Playgroud)
该程序没有抛出异常,但也没有打印任何内容。不确定这是否有帮助,但我确实觉得很好奇......