【问题标题】:Dynamically creating functions and threads in Python在 Python 中动态创建函数和线程
【发布时间】:2016-10-11 13:54:45
【问题描述】:

我有一个充满命令的数组,我想同时执行所有命令。

到目前为止,我有:

import threading

...

def MyThread0():
    exec commandArray[0]

def MyThread1():
    exec commandArray[1]

t1 = threading.Thread(target=MyThread0(), args=[]).start()
t2 = threading.Thread(target=MyThread1(), args=[]).start()

虽然如果只有两个线程这仍然是可以接受的(至少它似乎可以工作),但如果 commandArray 的长度在运行时未知,则肯定不是。对于 x 个线程,我如何有效地做到这一点?

PS:这完全有可能是垃圾,因为我是多线程新手。非常感谢建设性的批评。

【问题讨论】:

  • 对于初学者,在创建线程时,您不希望在函数名称后加上()。这将在评估该行之前调用该函数。

标签: python multithreading python-2.7


【解决方案1】:

如果我正确理解你的问题,应该是这样的:

    import threading

    ...
    command_array = ...
    number_of_commands = len(command_array)
    ...

    def run_the_command(index):
        exec command_array[index]

    threads = []
    for i in range(number_of_commands):    
        t = threading.Thread(target=run_the_command, args=(i,))
        t.start()
        threads.append(t)

注意:

  1. 传递run_it_boy 而不是run_it_boy(),因为您现在不想调用它,而是让线程模块来做。
  2. 鼓励使用snake_case作为函数/方法名和变量名,CamelCase是类名。

替代方案

在我看来,最好使用线程池。

【讨论】:

  • .start() 不返回任何内容,因此分配是无用的。
  • @DeepSpace 谢谢
  • NameError: name 't' is not defined :D
【解决方案2】:

对于初学者,在创建线程时,您不希望在函数名称后面加上()。这将在评估行之前调用该函数。

其次,.start() 不会返回任何内容,因此您对t1t2 的分配是无用的。

您可以做的是,并且比您拥有的代码更具动态性,类似于以下内容:

import threading

def func1():
    pass

def func2():
    pass

def func3():
    pass

funcs_to_run = [func1, func2, func3]  

threads = [threading.Thread(target=func, args=[]) for func in funcs_to_run]

这当然是假设您希望每个线程执行不同的功能。

然后启动线程:

 for thread in threads:
     thread.start()

【讨论】:

  • 这丝毫没有解决我的问题,我认为你根本没有理解我的问题。我不想写出这些函数/线程,因为我不知道我需要多少(例如,你使用了 3,但也可能是 20)。
猜你喜欢
  • 2012-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
相关资源
最近更新 更多