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

标签 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: 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/

相关文章:

python - 有Python轻量级GUI库吗?

python - 在 Python 生成器中使用 for...else

python - 在 Python 中类似矩阵的二维数组打印

c++ - `decay_copy` 对象的构造函数中的 `std::thread` 有何作用?

java - Java 中的素数生成线程打印两次

c++ - av_read_pause 和 av_read_play 挂了一个线程

Python 2.7 类型错误 : __init__() takes exactly 4 arguments (1 given)

python - 使用 Python 的 str.format() 方法使用十六进制、八进制或二进制整数作为参数索引时出现 KeyError

python - 带有 Flask 的 SQLAlchemy 无法连接到数据库以进行原始 SQL 查询?

python - CountVectorizer 矩阵随新的分类测试数据变化?