简体   繁体   English

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

[英]passing function to thread.start_new_thread through dictionary

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 and fun2 are returning strings. fun1和fun2返回字符串。 I am able to call these functions using approach 1 but not able to call using approach 2. Getting error as shown below. 我可以使用方法1调用这些函数,但不能使用方法2调用。出现错误,如下所示。 But approach 1 already proved that these are callable. 但是方法1已经证明这些是可以调用的。

thread.start_new_thread(fdict[random.randint(0,1)],())

TypeError : first arg must be callable TypeError :第一个arg必须可调用

The values of fdict are not functions; fdict的值不是函数; they are values returned from func1() and func2() respectively. 它们是分别从func1()func2()返回的值。

>>> fdict = {0: fun1, 1: fun2}
>>> thread.start_new_thread(fdict[random.randint(0,1)], ())

thread is a very low level library where there is no way of joining threads so when your main program finishes before any thread finishes executing its task, you'll be likely to get errors. thread是一个非常低级的库,其中没有连接线程的方法,因此当主程序在任何线程完成执行任务之前完成时,您很可能会出错。

You should use threading.Thread class to prevent these kind of issues from happening: 您应该使用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.

You can see the threading documentation for more information. 您可以查看线程文档以了解更多信息。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM