简体   繁体   中英

Simple threading in Python 2.6 using thread.start_new_thread()

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::

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

Original exception was:

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

You need to wait until your Thread finishes its work, so you have to use 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

Put while loop at last then it will work for you.

I tried it in Python 2.5 on a mac, after changing

except Exception as errtxt:

to

except Exception, errtxt:

The program did not throw an exception but also did not print anything. Not sure if that is helpful, but I do find it curious...

When I ran this code in Python 2.6 it worked, is it possible you have open threads already that are locked on the function? I recommend closing Python completely, checking your running processes to make sure nothing of yours is running and try again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM