使用thread.start_new_thread()在Python 2.6中进行简单线程化 [英] Simple threading in Python 2.6 using thread.start_new_thread()

查看:193
本文介绍了使用thread.start_new_thread()在Python 2.6中进行简单线程化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注有关简单线程的教程.他们给出了这个例子,当我尝试使用它时,我从解释器中收到了无法理解的错误.您能告诉我为什么这不起作用吗?我在使用Python 2.6当前版本的WinXP SP3中

I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current

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

执行此操作将导致::

Executing this results in::

由...启动的线程中未处理的异常 sys.excepthook错误:

Unhandled exception in thread started by Error in sys.excepthook:

最初的例外是:

错误中丢失的信息实际上是 输出中的.

The information missing in the error is actually missing in the output.

推荐答案

问题是您的主线程在新线程有时间完成之前就已退出.解决方案是在主线程上等待.

The problem is that your main thread has quit before your new thread has time to finish. The solution is to wait at your main thread.

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)

作为旁注,您可能想使用线程模块.您的主线程将等待所有这些类型的线程关闭,然后退出:

As a side note, you probably want to use the threading module. Your main thread will wait for all of those types of threads to be closed before exiting:

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.start_new_thread()在Python 2.6中进行简单线程化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆