2011-04-07 69 views
1

我可以帮助将此代码从线程转换为Mutliprocess。 然后任何人都可以帮助转换这个代码usinf扭曲。线程与多进程vs Python中的扭曲

会不会有使用扭曲到Python的内上传分贝
VS外部工具的增益。

import os, pyodbc, sys, threading, Queue 


class WorkerThread(threading.Thread): 
    def __init__(self, queue): 
     threading.Thread.__init__(self) 
     self.queue = queue 

    def run(self): 
     while 1: 
      try: # take a job from the queue 
       type = self.queue.get_nowait() 

      except Queue.Empty: 
       raise SystemExit 

      try: 
       cxn = pyodbc.connect('DSN=MySQL;PWD=MLML;Option=3') 
       csr = cxn.cursor()  
       # Inserts,update, CRUD 

      except: 
       # count = count +1 
       print 'DB Error', type 

if __name__ == '__main__': 
    connections = 25 

    sml = ('A', 'B', 'C','D',) 
    # build a queue with tuples 
    queue = Queue.Queue() 

    for row in sml: 
     if not row or row[0] == "#": 
      continue 
     queue.put(row) 

    threads = [] 
    for dummy in range(connections): 
     t = WorkerThread(queue) 
     t.start() 
     threads.append(t) 

    # wait for all threads to finish 
    for thread in threads: 
     thread.join() 

    sys.stdout.flush() 

#csr.close() 
#cxn.close() 
print 'Finish' 
+8

您有没有具体的问题,或者您真的只是想让我们为您编写代码? – nmichaels 2011-04-07 17:29:16

+0

我无法读取可变缩进的python-pseudo代码。你能介意纠正你的缩进。甚至发布一个工作示例? – MattH 2011-04-07 17:30:05

+0

更新了代码... – Merlin 2011-04-07 22:14:11

回答

1

更新:JP提到txpostgrestxmysql模块,我不知道的。这些允许Twisted以异步方式访问两个数据库(不使用线程池)。

请注意,如果您决定使用Twisted的企业adbapi,它将最终使用线程池来处理数据库连接,大致等同于您现有的示例。请参阅docs on using Twisted's enterprise database module

您应该能够直接将您的基于线程/队列的代码转换为使用多处理模块,通过用Process实例取代线程,以及使用多处理Queue实现。请参阅multiprocessing docs

+0

您可以使用txpostgres或txmysql与没有线程的postgres和mysql交谈。 – 2011-04-07 18:49:58

+0

@JP我不知道这些项目,谢谢。我更新了答案。 – samplebias 2011-04-07 18:58:15