【问题标题】:Threading vs Multiprocess vs Twisted in PythonPython中的线程vs多进程vs Twisted
【发布时间】:2011-04-07 17:24:20
【问题描述】:

我能否帮助我将此代码从 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'  

【问题讨论】:

  • 您是否有具体问题,或者您真的只是想让我们为您编写代码?
  • 我在阅读您的可变缩进 python 伪代码时遇到了问题。你能介意纠正你的缩进吗?甚至发布一个工作示例?
  • +1 nmichaels 这看起来不像是个问题。

标签: python mysql multithreading twisted multiprocessing


【解决方案1】:

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

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

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

【讨论】:

  • 您可以使用 txpostgres 或 txmysql 与 postgres 和 mysql 进行无线程对话。
  • @JP 我不知道这些项目,谢谢。我更新了答案。
猜你喜欢
  • 2011-10-13
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多