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: first arg must be callable
最佳答案
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.
您可以看到threading文档以获取更多信息。
希望这有帮助。
关于python - 通过字典将函数传递给 thread.start_new_thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529481/