[英]Threading vs Multiprocess vs Twisted in Python
我可以得到幫助,將此代碼從Threading轉換為Mutliprocess。 然后任何人都可以幫助扭曲此代碼。
使用twisted上傳數據庫會有好處嗎?
在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'
更新 :JP提到了我不知道的txpostgres和txmysql模塊。 這些允許Twisted異步訪問兩個數據庫(無需使用線程池)。
請注意,如果您決定使用Twisted的企業adbapi,它將最終使用線程池來處理數據庫連接,大致等同於現有示例。 請參閱有關使用Twisted的企業數據庫模塊的文檔 。
通過用Process
實例替換線程,並使用multiprocessing Queue
實現,您應該能夠直接將基於線程/隊列的代碼轉換為使用多處理模塊。 請參閱多處理文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.