线程代码的例外

时间:2015-09-29 12:00:00

标签: multithreading python-2.7

    import thread
    import time

    #Define a function for the thread
    def Print_Time(threadname,delay):
        count = 0
        while count < 5:
            time.sleep(delay)
            count += 1
            print "%s %s" %(threadname,time.ctime( time.time() ))

    #create two threads
    try:
        thread.start_new_thread(Print_Time("Thread1",2))
        thread.start_new_thread(Print_Time("Thread2",4))
    except:
        print "Error: unable to start thread"

当我运行此代码时,会在输出中生成并打印一次第一个线程。第二个线程将被生成并发生异常。

请帮助解决此异常。提前谢谢。

1 个答案:

答案 0 :(得分:0)

为什么使用try-except并放弃该异常,为您提供更多信息?您自己的错误消息Error: unable to start thread显然不会为您提供足够的信息。

try:
    pass # ...
except Exception, e:
    print(e) # start_new_thread expected at least 2 arguments, got 1

当您避开try或打印出异常时,您会发现将参数传递给start_new_thread的方式有问题。从文档中,您可以看到参数的传递方式。

  

thread.start_new_thread(function,args [,kwargs])

# False - you execute Print_time on your own
# and pass the return value to start_new_thread
thread.start_new_thread(Print_time("Thread1",2))

# Correct
thread.start_new_thread(Print_time, ("Thread1",2))
thread.start_new_thread(Print_time, ("Thread2",4))

请记住,您的主线程将在线程完成之前完成。等待他们使用计时器或更好地使用threading  这可以帮助你等待你开始的线程。