fdict= {0: fun1(), 1: fun2()}
# approach 1 : working fine, printing string
print fdict[random.randint(0,1)]
# approach 2 calling
thread.start_new_thread(fdict[random.randint(0,1)],())
#I also tried following approach
fdict= {0: fun1, 1: fun2}
thread.start_new_thread(fdict[random.randint(0,1)](),())fun1和fun2正在返回字符串。我可以使用方法1调用这些函数,但不能使用方法2调用。获取错误如下所示。但是,方法1已经证明了它们是可调用的。
thread.start_new_thread(fdict[random.randint(0,1)],())TypeError:第一个arg必须是可调用的
发布于 2015-07-21 02:47:25
fdict的值不是函数;它们分别是从func1()和func2()返回的值。
>>> fdict = {0: fun1, 1: fun2}
>>> thread.start_new_thread(fdict[random.randint(0,1)], ())thread是一个非常低级别的库,无法连接线程,所以当您的主程序在任何线程执行其任务之前完成时,很可能会出现错误。
您应该使用threading.Thread类来防止此类问题的发生:
>>> from threading import Thread
>>> fdict = {0: fun1, 1: fun2}
>>> t = Thread(target=fdict[random.randint(0,1)], args=())
>>> t.deamon = True
>>> t.start()
>>> t.join() # main program will wait for thread to finish its task.您可以查看穿线文档以获得更多信息。
希望这能有所帮助。
https://stackoverflow.com/questions/31529481
复制相似问题