如何先从一个函数执行线程,然后再从另一个函数执行线程?

2024-10-01 05:00:47 发布

您现在位置:Python中文网/ 问答频道 /正文

@chepner

我最初是这样做的:

class Cub:
    def __init__(self, lenght, width, height):
        self.lenght = lenght
        self.width = width
        self.height = height

    def volume(self):
        return self.lenght * self.width * self.height
        

    def calclenght(self):
        return ((self.lenght * 12))

    


def main():
    cub = Cub(3, 4, 5)
    print("Volume = ", cub.volume())
    print("Total lenght = ", cub.calclenght())


if __name__=="__main__":
    main()

结果是:体积=60,长度=36。这是我必须完成的任务:

创建一个类,该类将用于实例化立方体形状的对象。定义一种用于计算立方体体积的方法和另一种用于计算立方体所有边的总长度的方法

将这些方法放在线程中,首先运行第二个线程方法,然后在成功完成后运行第一个线程方法。在此过程中,必须关闭主线

创建两个对象,在这两个对象上调用每个已创建的方法

使用“打印”命令显示这些方法的结果


Tags: 对象方法selfreturnmaindefwidth线程
1条回答
网友
1楼 · 发布于 2024-10-01 05:00:47

老实说,这个任务是一个可怕的线程示例,因为在这里完全没有必要这么做。不管怎样,这都是一种方法

实际上,我不确定任务是想让您直接在对象函数中打印结果,还是作为主程序的一部分打印结果。后者就是我在这里所做的,尽管直接分配给可变对象并不是您真正想要做的(它) 但在这种情况下,这并不重要)。如果这是预期的结果,请改用thread queue,它允许您以安全的方式直接获取线程的返回值

import threading

# thread outputs are done by passing in a mutable object to the thread's run function
#   this is not the best way
#   generally, if you have to use threads, you don't expect them to return anything
#   the proper way to do this would be to use python's queue, which I haven't done here

class cuboid:
    x: float
    y: float
    z: float

    def __init__(
        self,
        x: float,
        y: float,
        z: float
    ):
        self.x = x
        self.y = y
        self.z = z

    # output is a mutable object; as an argument these are basically like pointers, they're not copies of objects
    #   this is *not* thread safe, though this isn't a problem in this case as we're joining the threads anyway
    def getVolume(
        self,
        output,
        index: int
    ) -> None:
        output[index] = self.x * self.y * self.z

    # same thing here
    def getSideLength(
        self,
        output,
        index: int
    ) -> None:
        # the total side length of a cuboid (not a cube!) is calculated differently
        output[index] = self.x * 4 + self.y * 4 + self.z * 4

# sizes to use as initialization parameters for the 2 cuboid objects
sizes = [
    [
        1,
        2,
        3
    ],
    [
        4,
        5,
        6
    ]
]

# mutable object to use as output
#   output[index of cuboid][0 = volume, 1 = length]
#   (could also use a dict for this to make it easier to understand)
output = []

# iterate through initialization sizes
for i in range(
    0,
    len(sizes)
):
    # populate the output list
    output.append(
        [None, None]
    )

    # instantiate cuboid
    cuboi = cuboid(
        *sizes[i]
    )
    
    # create threads
    #   notice the passed in args
    thread1 = threading.Thread(
        target=cuboi.getVolume,
        args=(
            # mutable sub-list
            output[i], 
            # index to assign to of sub-list (effectively output[i][0])
            0
        )
    )
    # same thing here
    thread2 = threading.Thread(
        target=cuboi.getSideLength,
        args=(
            output[i], 
            1
        )
    )

    # start and join the threads
    #   joining a thread blocks the thread which calls .join(), which is the main thread in this case, until it finishes
    thread2.start()
    thread2.join()

    # same thing here
    thread1.start()
    thread1.join()

    # print value of output
    print(
        "Volume of Cuboid #%s: %s" % (i, output[i][0])
    )
    print(
        "Length of Cuboid #%s: %s" % (i, output[i][1])
    )

这将输出:

Volume of Cuboid #0: 6
Length of Cuboid #0: 24
Volume of Cuboid #1: 120
Length of Cuboid #1: 60

相关问题 更多 >