python-3.xasynchronouspython-asynciopython-multithreadingasyncsocket

Python3.5 Async execution similar to Java-SpringBoot @EnableAsync @Async annotations


I want to simulate an async python3.5 function similar to what we have in Java with the SpringBoot @EnableAsync @Async annotation.

In Spring, methods annotated with the @Async annotation, control is returned to the previous method soon after the method invocation.

import threading
import re
import subprocess

x = None

class Printer

    def caller():
        if(x == True):
            x = False # Stop the prev executing while-loop.
            print('While-loop stopped & spawning a new one.')

        x = True
        p = threading.Thread(target=self.print_cpu_data())
        p.start()
        print('Thread is Alive: {0}'.format(p.is_alive())) # This line never gets executed!!!

    # Ideally I want this function to return control to the caller function before executing
    # the code inside the print_cpu_data function
    def print_cpu_data(self):
                # At this point control should returned to the caller() function
                # while the rest of the execution continues behind the scenes.
                while x:
                     cpu = subprocess.getoutput('cat /sys/class/thermal/thermal_zone0/temp')
                     gpu = subprocess.getoutput('/opt/vc/bin/vcgencmd measure_temp')
                     cpu = re.findall(r'[-+]?\d*\.?\d+|[-+]?\d+', cpu)
                     gpu = re.findall(r'[-+]?\d*\.?\d+|[-+]?\d+', gpu)
                     cpu = float(cpu[0]) / 1000
                     gpu = float(gpu[0])
                     print('CPU: {0:.2f}{2}C\tGPU: {1:.2f}{2}C'.format(cpu, gpu, '°'))
                     time.sleep(1.0)

Is such a scenario possible in Python3.x? I have spent hours on such a simple case.


Solution

  • Use threading.Thread(target=self.print_cpu_data), not threading.Thread(target=self.print_cpu_data()) - note that the parenthesis are removed. What you have now is explicitly calling print_cpu_data() in the main thread, rather than sending it off to the background thread to be called. So your program never even gets to create/start the Thread object.