Simple threading in Python 2.6 using thread.start_new_thread()

前端 未结 5 2184
野的像风
野的像风 2020-12-15 09:04

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 m

5条回答
  •  青春惊慌失措
    2020-12-15 09:10

    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
    

提交回复
热议问题