简体   繁体   English

与python并行执行代码

[英]Executing code in parallel with python

I am trying to use multithreading in python. 我正在尝试在python中使用多线程。 I wrote the following code to start. 我写了以下代码开始。 It is supposed to compute, in parallel, the squares of numbers contained in a list and to return the result in a list named 'result'. 它应该并行计算列表中包含的数字平方,并将结果返回到名为“结果”的列表中。 I wrote this in order to parallelize a script that contains a for loop. 我写这是为了并行化包含for循环的脚本。

However, I get a TypeError telling me that 'int object is not callable'. 但是,我收到一个TypeError告诉我'int object is not callable'。 I am guessing this is because of this line of code: thr.append(threading.Thread(target=square(k))) : In the examples I read, target was a function. 我猜这是因为这行代码: thr.append(threading.Thread(target=square(k))) :在我阅读的示例中,target是一个函数。 But in my example, I will need to call the same function with different arguments. 但是在我的示例中,我将需要使用不同的参数调用同一函数。 How can I do that? 我怎样才能做到这一点?

>>> def square(c):
...     return c^2
...     result.append(c^2)
... 



>>> def sqr():
...     thr = []
...     for k in l:
...         thr.append(threading.Thread(target=square(k)))
...     for t in thr:
...         t.start()
...     for i in thr:
...         t.join()

Try this: 尝试这个:

thr.append(threading.Thread(target=square, args=(k,)))

instead of thr.append(threading.Thread(target=square(k))) 而不是thr.append(threading.Thread(target=square(k)))

You get that error because you end up calling the function in your code. 之所以收到该错误,是因为最终在代码中调用了该函数。 When the function is called, square(k) returns an int which is not callable. 调用该函数时, square(k)返回一个不可调用的int

Refer to the documentation . 请参阅文档

Also, as unutbu has pointed out in the comments to the question, you are doing an XOR and not computing the square. 另外,正如unutbu在对该问题的评论中指出的那样,您正在执行XOR而不是计算平方。 Squares are computed this way: x**2 and not x^2 . 平方的计算方式是: x**2而不是x^2

Also, you are returning the result before adding it to the list, so you might want to reverse the order of the two lines in your function definition if you want to add the square of the number to the list, result . 同样,您要在将结果添加到列表之前返回结果,因此,如果要将数字的平方添加到列表result ,则可能要颠倒函数定义中两行的顺序。

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

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