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

问题描述 投票:0回答:1

我想使用SpringBoot @EnableAsync @Async annotation模拟类似于Java中的异步python3.5函数。

在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中是否可能出现这种情况?在这样一个简单的案例上,我花了几个小时。

我想使用SpringBoot @EnableAsync @Async注释来模拟类似于Java中的异步python3.5函数。在Spring中,使用@Async注释进行注释的方法,控件是...

python-3.x asynchronous python-asyncio python-multithreading asyncsocket
1个回答
0
投票

使用threading.Thread(target=self.print_cpu_data),而不是threading.Thread(target=self.print_cpu_data())-请注意,括号已删除。您现在拥有的是在主线程中显式调用print_cpu_data(),而不是将其发送给要调用的后台线程。因此,您的程序甚至无法创建/启动Thread对象。

© www.soinside.com 2019 - 2024. All rights reserved.