python - 线程与多处理与 Python 中的 Twisted

标签 python mysql multithreading twisted multiprocessing

我能否获得帮助,将此代码从 Threading 转换为 Mutliprocess。 那么谁能帮忙把这段代码用inf twisted转换一下。

使用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'  

最佳答案

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

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

您应该能够直接将基于线程/队列的代码转换为使用多处理模块,方法是将线程替换为Process 实例,并使用多处理Queue执行。查看multiprocessing docs .

关于python - 线程与多处理与 Python 中的 Twisted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5585055/

相关文章:

c# - 将数据插入数据库

java - AudioRecord 线程中的处理

python - 创建 dict 和 Exception 的子类

php - 如何在codeigniter中加入多个连接

php - 从两个表中选择数据时出错

python - 并发.futures.ThreadPoolExecutor不打印错误

python,多线程,在公共(public)文件上使用 pandas "to_csv"安全吗?

python - 调整矩阵数组乘法以使用 Numpy Tensordot

python - 使用 2d 数组对 3d numpy 数组进行索引

python - 如何等待 celery 生产者 celery 工作人员完成其任务