简体   繁体   中英

How to thread from a function first, and then another one?

@chepner

This is how i initially did it:

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()

results are: volume = 60, lenght = 36. This is the task i have to do:

Create a class that will be used to instantiate cube-shaped objects. Define a method for calculating the volume of a cube and another method for calculating the total length of all sides of a cube.

Place these methods in the threads, run the second threaded method first, and, after successful completion, run the first. During this process, the main wire must be turned off.

Create two objects over which each of the created methods will be called.

Display the results of these methods with the print command.

This task is honestly a horrible example of threading, as it's completely unnecessary to do here. Either way, this is one way of doing it.

I'm not actually sure if the task wants you to print the results in the object's function directly, or as part of the main program. The latter is what I've done here, although directly assigning to a mutable object is not what you would actually want to do (it doesn't actually matter in this case, however). If this is what was expected, use a thread queue instead, which allows you to directly get the return values of threads in a safe manner.

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])
    )

Which will output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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