Skip to content

Instantly share code, notes, and snippets.

@apahim
Last active March 23, 2016 19:45
Show Gist options
  • Save apahim/dcc61af05d1d7121f6cd to your computer and use it in GitHub Desktop.
Save apahim/dcc61af05d1d7121f6cd to your computer and use it in GitHub Desktop.
import threading
import time
import random
class VmsBackup(object):
def __init__(self):
self.vms = ['vm01', 'vm02', 'vm03', 'vm04', 'vm05', 'vm06', 'vm07', 'vm08', 'vm09']
def get_vm_to_backup(self):
try:
return self.vms[0]
except:
return None
def set_vm_as_backed_up(self, vm):
self.vms.remove(vm)
def run(self, Thread, vm):
name=threading.current_thread().name
Thread.activate(name)
# Aqui eh pra chamar a funcao de backup. To chamando um sleep p ilustrar
print 'Fazendo backup da vm %s' % vm
print 'Threads: %s' % str(Thread).strip()
time.sleep(random.randint(5,10))
print 'Terminou backup da vm %s' % vm
Thread.deactivate(name)
class Threads(object):
def __init__(self):
super(Threads, self).__init__()
self.active=[]
self.lock=threading.Lock()
def activate(self, name):
with self.lock:
self.active.append(name)
def deactivate(self, name):
with self.lock:
self.active.remove(name)
def count(self):
with self.lock:
return len(self.active)
def __str__(self):
with self.lock:
return str(self.active)
if __name__ == '__main__':
Thread = Threads()
backup = VmsBackup()
jobs=[]
while backup.get_vm_to_backup():
if threading.activeCount() > 2:
print 'Esperando thread livre...'
else:
vm = backup.get_vm_to_backup()
job = threading.Thread(target=backup.run, args=(Thread, vm))
backup.set_vm_as_backed_up(vm)
job.daemon = True
job.start()
time.sleep(1)
print 'PARECE que terminei :)'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment