[错误]: 使用Python3执行多线程脚本时,使用threading.Thread()出现问题

3
下面的代码示例是我尝试创建的一个小脚本。在这个脚本中,有两个函数:calculate_the_square(takes_the_given_array)calculate_the_cube(takes_the_given_array)
我创建了两个线程threa_01和thread_02,并告诉它们执行我想要的函数。在args变量中,我发送了要计算的数组(args=array)。在目标变量中,我发送了特定线程要运行的函数名称(target=calculate_the_squaretarget=calculate_the_cube)。然后我开始执行线程,并让它们加入。
不幸的是,当我执行时,我遇到了以下问题: 问题
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
TypeError: calculate_the_square() takes 1 positional argument but 6 were given

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
TypeError: calculate_the_cube() takes 1 positional argument but 6 were given


Process finished with exit code 0

期望的输出结果(必须是混合的,但我写了通用结果而不是多线程的)

Cube result:  5832
Cube result:  778688
Cube result:  2000376
Cube result: 281011375 
Cube result:  967361669
Cube result:  1006012008
Square result:  324 
Square result:  8464
Square result:  15876
Square result:  429025
Square result:  978121
Square result:  1004004
The program finished in : ...... SOME TIME

代码示例

import time
import threading

def calculate_the_square(variables):

    for var in variables:
        time.sleep(0.5)     # Insert a sleep just to count the time that needs to be completed
        print("Square result: ", var*var)

def calculate_the_cube(variables):
    time.sleep(0.5)     # Insert a sleep just to count the time that needs to be completed
    for var in variables:
        print("Cube result: ", var*var*var)


keeping_time = time.time()              # Keeping the starting time
array = [18, 92, 126, 655, 989, 1002]  # Random given numbers.



thread_01 = threading.Thread(target=calculate_the_square, args=(array))     # Creating threadh No1 and the target make this thread to focus on this function, sending the value that is saved in tha variable args.
thread_02 = threading.Thread(target=calculate_the_cube, args=(array))       # Creating threadh No2 and the target make this thread to focus on this function, sending the value that is saved in tha variable args.


thread_01.start()   # Starting the thread 1
thread_02.start()   # Starting the thread 2

thread_01.join() # Waits until the first thread is finished. Better switching between the threads. Maybe not now (only 2 threads) but if we had 10 and more it would be helpful.
thread_02.join()

print("The program finished in :", time.time()-keeping_time)

你能帮我解决这个问题吗?我做错了什么吗?

提前感谢您的时间!

2个回答

5
< p > args 参数必须是一个元组。您需要进行更改。
thread_01 = threading.Thread(target=calculate_the_square, args=(array))
thread_02 = threading.Thread(target=calculate_the_cube, args=(array))

转化为

thread_01 = threading.Thread(target=calculate_the_square, args=(array,))
thread_02 = threading.Thread(target=calculate_the_cube, args=(array,))

你可以通过输入解释器来检查它:

type((1))
type((1,))

输出:

<class 'int'>
<class 'tuple'>

元组代表什么? - dpapadopoulos
1
元组就像是一个不可修改的列表,你可以在这里了解更多相关内容。在这种情况下,它代表函数参数。如果你的 calculate_the_square 函数接受一个数组和一个字符串作为参数,那么你需要将 args 设置为 args=(variables, "example string"),并将函数声明为 def calculate_the_square(variables, str): - kgorak

5

我将使用第一个答案中的内容,并解释:

  • 什么是元组及其作用:元组类似于列表。两者之间的区别在于,一旦分配了元组的元素,就无法更改它们,而在列表中,元素可以更改。
  • 元组的优点:1)我们通常使用元组来存储异构(不同类型)数据类型,而使用列表存储同构(相似类型)数据类型;2)由于元组是不可变的,因此遍历元组比遍历列表更快。因此,有轻微的性能提升;3)包含不可变元素的元组可以用作字典的键。这在列表中是不可能的;4)如果您有不会更改的数据,将其实现为元组将保证其保持只读。

所以,从我看到的内容来看,您没有问题理解多线程逻辑,但您可能没有看到代码中元组的原因。现在我认为这很清楚了。当然,第一个答案的解决方案是正确的。使用逗号就足以声明您想要在此函数中传递什么也不是:

thread_01 = threading.Thread(target=calculate_the_square, args=(array,))
thread_02 = threading.Thread(target=calculate_the_cube, args=(array,))

我看到了第一篇回答中的资源链接。我还想让你看看这里。我认为这更有用,也更容易理解整个情况。

再见!


1
哇,你的回答确实更加详细。从我所看到的来看,那是真的。我遇到了元组的问题,而不是多线程的问题。我认为从逻辑上讲,你的回答更好。再次感谢你的时间! - dpapadopoulos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接