使用多个变量进行线程化

时间:2017-03-25 14:13:35

标签: python multithreading variables import

我有一个小的python脚本,旨在并行运行2到3个函数。 这些脚本似乎有效,因为我确实得到了答案,但它以一个例外结束:

import threading

Variable2="V2"
Variable1="V1"
Variable12="V1"
Variable22="V2"
Variable23="V3"

def func1(Variable1,Variable2):
    print ("This is my  fisrt fucntion ")
    print ("My first variable is : %s ") % (Variable1)
    print ("My second variable is : %s ") % (Variable2)

def func2(Variable12,Variable22,Variable23):
    print ("This is my  fisrt fucntion ")
    print ("My first variable is : %s ") % (Variable12)
    print ("My second variable is : %s ") % (Variable22)
    print ("My third variable is : %s ") % (Variable23)

def runInParallel(*fns):
    proc = []
    for fn, arg in fns:
        p = threading.Thread(target=fn, args=(arg,))
        p.start()
        proc.append(p)
    for p in proc:
        p.join()


runInParallel( ( func1(Variable1,Variable2,) ), (func2(Variable12,Variable22,Variable23,) ) )

它给了我以下内容:

This is my  fisrt fucntion
My first variable is : V1
My second variable is : V2
This is my  fisrt fucntion
My first variable is : V1
My second variable is : V2
My third variable is : V3
Traceback (most recent call last):
File "testpara.py", line 69, in <module>
    runInParallel( ( func1(Variable1,Variable2,) ) , (func2(Variable12,Variable22,Variable23,) ) )
File "testpara.py", line 61, in runInParallel
    for fn, arg in fns:
TypeError: 'NoneType' object is not iterable

我检查了here并且似​​乎线程的一个参数是通过( group=None, target=None, name=None, args=(), kwargs={} )的注释。

有任何线索吗?

编辑:这似乎与 here不同,因为该答案中的变量与更新后的值相同。

1 个答案:

答案 0 :(得分:2)

正如@Mark Dickinson在评论中指出的那样,你没有正确地调用runInParallel(),你实际上正在调用调用序列中的每个函数(这导致每个函数的返回值,{{ 1}},作为参数'值'传递。

修复很简单,只需更改None中的一行,并在调用时添加一些逗号:

runInParallel()

感谢Mark Dickinson纠正我的纠正。 def runInParallel(*fns): proc = [] for fn, arg in fns: p = threading.Thread(target=fn, args=arg) # was args=(arg,) p.start() proc.append(p) for p in proc: p.join() runInParallel((func1, (Variable1, Variable2,)), (func2, (Variable12, Variable22, Variable23,)))

相关问题