Python3.5 类似Java的异步执行-SpringBoot @EnableAsync @Async注解

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

我想用 SpringBoot @EnableAsync @Async annotation.[= 模拟一个类似于我们在 Java 中的异步 python3.5 函数14=]

在 Spring 中,使用 @Async 注释进行注释的方法,控制在方法调用后立即返回到前一个方法。

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)

这种情况在Python3.x有可能吗?我在这么简单的案例上花了好几个小时。

使用 threading.Thread(target=self.print_cpu_data),而不是 threading.Thread(target=self.print_cpu_data()) - 请注意括号已被删除。您现在拥有的是在主线程中显式调用 print_cpu_data(),而不是将其发送到要调用的后台线程。所以你的程序永远不会到达 create/start Thread 对象。