synchmultithread.py

1041阅读 0评论2010-11-30 atyu30
分类:Oracle

#File: synchmultithread.py
#Using locks for synchronization in a multithreaded script
import sys
import cx_Oracle
import threading
from xml.dom.minidom import parseString
from urllib import urlopen
 
#subclass of threading.Thread
class SynchThread(threading.Thread):
   def __init__(self, cur, query, dom):
     threading.Thread.__init__(self)
     self.cur = cur
     self.query = query[1]
     self.tag = query[0]
     self.dom = dom
   def run(self):
     self.cur.execute(self.query)
     rslt = self.cur.fetchone()[0]
     self.cur.close()
     mutex.acquire()
     sal = self.dom.getElementsByTagName('salary')[0]
     newtag = self.dom.createElement(self.tag)
     newtext = self.dom.createTextNode('%s'%rslt)
     newtag.appendChild(newtext)
     sal.appendChild(newtag)
     mutex.release()
#main thread starts here
domdoc = parseString('')
dbconn = cx_Oracle.connect('hr', 'hr', '127.0.0.1/XE',threaded=True)
mutex = threading.Lock()
queries = {}
queries['avg'] = "SELECT AVG(salary) FROM employees"
queries['max'] = "SELECT MAX(salary) FROM employees"
th = []
for i, query in enumerate(queries.items()):
   cur = dbconn.cursor()
   th.append(SynchThread(cur, query, domdoc))
   th[i].start()
#forcing the main thread to wait until all child threads are done
for t in th:
   t.join()
#printing out the result xml document
domdoc.writexml(sys.stdout)

上一篇:RHEL 6 文件系统
下一篇:twistedsimple.py