我可以得到帮助将此代码从线程转换为多进程。那么有没有人可以使用inf . twisted.
来帮助转换这些代码?使用twisted来上传db会有好处吗
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'
Updated: JP提到txpostgres和txmysql模块,这是我不知道的。这允许Twisted异步访问两个数据库(不使用线程池)。
注意,如果您决定使用Twisted的企业adbapi,它最终将使用一个线程池来处理数据库连接,大致相当于您现有的示例。请参阅使用Twisted的企业数据库模块的文档。
你应该能够直接转换基于线程/队列的代码来使用多处理模块,通过用Process
实例替换你的线程,并使用多处理Queue
实现。