Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3343117
  • 博文数量: 815
  • 博客积分: 12898
  • 博客等级: 上将
  • 技术积分: 7883
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-25 09:57
文章分类

全部博文(815)

文章存档

2014年(1)

2011年(46)

2010年(192)

2009年(121)

2008年(70)

2007年(385)

分类: Oracle

2010-11-30 18:26:55

#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)

阅读(1017) | 评论(0) | 转发(0) |
0

上一篇:RHEL 6 文件系统

下一篇:twistedsimple.py

给主人留下些什么吧!~~