Python中的线程、进程和Twisted

1 投票
1 回答
1841 浏览
提问于 2025-04-16 15:17

我能不能请人帮我把这段代码从线程(Threading)转换成多进程(Multiprocess)?还有,能不能有人帮我把这段代码用Twisted来改写一下?

在Python中使用Twisted来上传数据库,和用外部工具相比,会有什么好处吗?

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 个回答

1

更新:JP提到了两个模块,txpostgrestxmysql,我之前并不知道。这些模块可以让Twisted异步地访问这两种数据库,也就是说,它们不需要使用线程池。

需要注意的是,如果你决定使用Twisted的企业版adbapi,它最终会使用线程池来处理数据库连接,这大致和你现有的例子是一样的。你可以查看Twisted企业数据库模块的文档

你应该可以直接把基于线程/队列的代码转换为使用多进程模块,只需将你的线程替换为Process实例,并使用多进程的Queue实现。有关更多信息,请查看多进程文档

撰写回答