Search code examples
pythonpython-3.xmultithreadingpython-multithreading

In what thread will calculations be performed?


I have following classes for example:

class CalculatorA:
    def functionA(self):
        #some calculations

class CalculatorB:
    def functionB(self):
        #some calculations

class CalculatorC:
    def functionC(self):
        #some calculations

class Aggregator:
    def __init__(self, objectA, objectB, objectC):
        self.objectA = objectA
        self.objectB = objectB
        self.objectC = objectC

    def aggregator_function(self):
        self.objectA.functionA()
        self.objectB.functionB()
        self.objectC.functionC()

class Worker(threading.Thread):
    def __init__(self,
                 objectA,
                 objectB,
                 objectC):
        threading.Thread.__init__(self)
        self.objectA = objectA
        self.objectB = objectB
        self.objectC = objectC

    def run(self):
        agregator = Aggregator(self.objectA, 
                                self.objectB, 
                                self.objectC)
        agregator.aggregator_function()

My main() function:

def main():
    objectA = CalculatorA()
    objectB = CalculatorB()
    objectC = CalculatorC()

worker = Worker(objectA, objectB, objectC)
worker.start()

I create objects of CalculatorA, CalculatorB, CalculatorC classes in the main() function and pass variables as parameters to the constructor of Worker. An object of the Worker class saves them. Later it passes the variables to the constructor of an Aggregator object in the run() function. It creates an Aggregator object in a separate thread of calculations. Aggregator calls functions functionA(), functionB(), functionC().

My question is, in what thread calculations of the functions functionA(), functionB(), functionC() will be performed? Will they be performed in the Worker thread, or in the main thread? Should I use threading.local storage, if in the main thread?


Solution

  • Functions are called in whatever thread the calling function is run in. The fact that they're object methods doesn't change this.

    Since self.objectA.functionA() is called from aggregator.aggregator_function(), and this is called from the Worker.run() method, it gets called in the Worker thread.