简体   繁体   English

在python的守护进程线程中运行对象方法

[英]Run an object method in a daemon thread in python

I am trying to simulate an environment with vms and trying to run an object method in background thread. 我试图用vms模拟环境,并试图在后台线程中运行对象方法。 My code looks like the following. 我的代码如下所示。

hyper_v.py file : hyper_v.py文件:

import random
from threading import Thread
from virtual_machine import VirtualMachine

class HyperV(object):
def __init__(self, hyperv_name):
    self.hyperv_name = hyperv_name
    self.vms_created = {}

def create_vm(self, vm_name):
    if vm_name not in self.vms_created:
        vm1 = VirtualMachine({'vm_name': vm_name})
        self.vms_created[vm_name] = vm1
        vm1.boot()
    else:
        print('VM:', vm_name, 'already exists')

def get_vm_stats(self, vm_name):
    print('vm stats of ', vm_name)
    print(self.vms_created[vm_name].get_values())

if __name__ == '__main__':
    hv = HyperV('temp')
    vm_name = 'test-vm'
    hv.create_vm(vm_name)
    print('getting vm stats')
    th2 = Thread(name='vm1_stats', target=hv.get_vm_stats(vm_name) )
    th2.start()

virtual_machine.py file in the same directory: 同一目录中的virtual_machine.py文件:

import random, time, uuid, json 
from threading import Thread

class VirtualMachine(object):
def __init__(self, interval = 2, *args, **kwargs):
    self.vm_id = str(uuid.uuid4())
    #self.vm_name = kwargs['vm_name']
    self.cpu_percentage = 0
    self.ram_percentage = 0
    self.disk_percentage = 0
    self.interval = interval

def boot(self):
    print('Bootingup', self.vm_id)
    th = Thread(name='vm1', target=self.update() )
    th.daemon = True      #Setting the thread as daemon thread to run in background
    print(th.isDaemon())  #This prints true 
    th.start()

def update(self):
    # This method needs to run in the background simulating an actual vm with changing values. 
    i = 0 
    while(i < 5 ): #Added counter for debugging, ideally this would be while(True) 
        i+=1 
        time.sleep(self.interval)
        print('updating', self.vm_id)
        self.cpu_percentage = round(random.uniform(0,100),2)
        self.ram_percentage = round(random.uniform(0,100),2)
        self.disk_percentage = round(random.uniform(0,100),2)

def get_values(self):
    return_json = {'cpu_percentage': self.cpu_percentage,
                   'ram_percentage': self.ram_percentage,
                   'disk_percentage': self.disk_percentage}
    return json.dumps(return_json)

The idea is to create a thread that keeps on updating the values and on request, we read the values of the vm object by calling the vm_obj.get_values() we would be creating multiple vm_objects to simulate multiple vms running in parallel and we need to get the information from a particular vm on request. 这个想法是创建一个线程,该线程会不断更新值并根据请求,我们通过调用vm_obj.get_values()读取vm对象的值,我们将创建多个vm_objects来模拟并行运行的多个vm,我们需要根据要求从特定虚拟机获取信息。

The problem, that I am facing, is that the update() function of the vm doesnot run in the background (even though the thread is set as daemon thread). 我面临的问题是,vm的update()函数无法在后台运行(即使该线程被设置为守护程序线程)。

The method call hv.get_vm_stats(vm_name) waits until the completion of vm_object.update() (which is called by vm_object.boot() ) and then prints the stats. 方法调用hv.get_vm_stats(vm_name)等待直到完成vm_object.update() (由vm_object.boot()调用),然后打印统计信息。 I would like to get the stats of the vm on request by keeping the vm_object.update() running in the background forever. 我想通过保持vm_object.update()永远在后台运行来获取请求时vm的统计信息。

Please share your thoughts if I am overlooking anything related to the basics. 如果我忽略了与基础知识相关的任何内容,请分享您的想法。 I tried looking into the issues related to the python threading library but I could not come to any conclusion. 我试图调查与python线程库相关的问题,但无法得出任何结论。 Any help is greatly appreciated. 任何帮助是极大的赞赏。 The next steps would be to have a REST api to call these functions to get the data of any vm but I am struck with this problem. 下一步将是使用REST api来调用这些函数以获取任何vm的数据,但我对这个问题感到震惊。

Thanks in advance, 提前致谢,

As pointed out by @Klaus D in the comments, my mistake was using the braces when specifying the target function in the thread definition, which resulted in the function being called right away. 正如@Klaus D在评论中指出的那样,我的错误是在线程定义中指定目标函数时使用了花括号,从而导致该函数立即被调用。

target=self.update() will call the method right away. target = self.update()将立即调用该方法。 Remove the () to hand the method over to the thread without calling it. 删除(),将方法移交给线程而不调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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