在python

时间:2019-02-27 02:42:55

标签: python multithreading python-3.6 python-multithreading

我正在尝试使用vms模拟环境,并尝试在后台线程中运行对象方法。我的代码如下所示。

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文件:

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)

这个想法是创建一个线程,该线程不断更新值并根据请求,我们通过调用vm_obj.get_values()读取vm对象的值,我们将创建多个vm_objects来模拟并行运行的多个vm。我们需要根据要求从特定虚拟机获取信息。

我面临的问题是,vm的update()函数不会在后台运行(即使该线程被设置为守护程序线程)。

方法调用 hv.get_vm_stats(vm_name)等待,直到完成 vm_object.update()(由 vm_object.boot()< / strong>),然后打印统计信息。我想通过保持 vm_object.update()永远在后台运行来获取请求时vm的统计信息。

如果我忽略了与基础知识相关的任何内容,请分享您的想法。我试图调查与python线程库相关的问题,但无法得出任何结论。任何帮助是极大的赞赏。下一步将是使用REST api来调用这些函数以获取任何vm的数据,但我对这个问题感到震惊。

谢谢,

1 个答案:

答案 0 :(得分:0)

正如@Klaus D在评论中指出的那样,我的错误是在线程定义中指定目标函数时使用了花括号,导致该函数立即被调用。

  

target = self.update()将立即调用该方法。删除()以   将方法移交给线程而不调用它。