ia64/xen-unstable

view tools/python/xen/xend/xenstore/xswatch.py @ 6673:63e226a5e272

Add python bindings for watches.
Uses a watcher thread with per-watch registered callbacks.
Signed-off-by: Christian Limpach <Christian.Limpach@cl.cam.ac.uk>
author cl349@firebug.cl.cam.ac.uk
date Wed Sep 07 12:47:45 2005 +0000 (2005-09-07)
parents
children e991ec23c318
line source
2 import select
3 import threading
4 from xen.lowlevel import xs
6 class xswatch:
8 watchThread = None
9 threadcond = threading.Condition()
10 xs = None
11 xslock = threading.Lock()
12 watches = []
14 def __init__(self, path, fn, args=(), kwargs={}):
15 self.fn = fn
16 self.args = args
17 self.kwargs = kwargs
18 xswatch.watchStart()
19 xswatch.xslock.acquire()
20 xswatch.xs.watch(path, self)
21 xswatch.xslock.release()
22 xswatch.watches.append(self)
24 def watchStart(cls):
25 cls.threadcond.acquire()
26 if cls.watchThread:
27 cls.threadcond.release()
28 return
29 cls.watchThread = threading.Thread(name="Watcher",
30 target=cls.watchMain)
31 cls.watchThread.setDaemon(True)
32 cls.watchThread.start()
33 while cls.xs == None:
34 cls.threadcond.wait()
35 cls.threadcond.release()
37 watchStart = classmethod(watchStart)
39 def watchMain(cls):
40 cls.threadcond.acquire()
41 cls.xs = xs.open()
42 cls.threadcond.notifyAll()
43 cls.threadcond.release()
44 while True:
45 try:
46 (ord, owr, oer) = select.select([ cls.xs ], [], [])
47 cls.xslock.acquire()
48 # reconfirm ready to read with lock
49 (ord, owr, oer) = select.select([ cls.xs ], [], [], 0.001)
50 if not cls.xs in ord:
51 cls.xslock.release()
52 continue
53 we = cls.xs.read_watch()
54 watch = we[1]
55 cls.xs.acknowledge_watch(watch)
56 cls.xslock.release()
57 except RuntimeError, ex:
58 print ex
59 raise
60 watch.fn(*watch.args, **watch.kwargs)
62 watchMain = classmethod(watchMain)