通过字典将函数传递给thread.start_new_thread

时间:2015-07-21 02:41:27

标签: python multithreading python-2.7 python-3.x

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必须是可调用的

1 个答案:

答案 0 :(得分:1)

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文档以获取更多信息。

希望这有帮助。