线程与多进程对比在Python中扭曲

时间:2011-04-07 17:24:20

标签: python mysql multithreading twisted multiprocessing

我可以获得帮助将此代码从Threading转换为Mutliprocess。 那么任何人都可以帮助我们扭转这段代码。

使用twisted来上传db会有收获吗 在Python与外部工具之间。

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'  

1 个答案:

答案 0 :(得分:1)

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

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

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