如何在python中实现Hollywood原则?

2024-10-03 02:46:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我计划将我的项目改为多进程,这样我可以使用更多的资源,下面是我的数据库模块代码

import pymysql
import threading
class tdb:
    def __init__(self):
        self.totalEffected = 0
        pass

    def start(self):
        self.conn = pymysql.connect(host='xxxx', port=3306, user='root', passwd='xxxx', db='xxxx', charset='utf8')

    def select(self,sql,args=None):
        cur = self.conn.cursor()
        cur.execute(sql,args)
        result = cur.fetchall()
        cur.close()
        return result

    def execute(self,sql,args=None):
        cur = self.conn.cursor()
        result = cur.execute(sql,args)
        cur.close()
        self.totalEffected+=result
        return result

#    def __commit(self,callback):

    def __commitCallback(self,result):
        print('commit result:',result)
        self.conn.close()

    def errorc(self,*args):
        print('error')

    def end(self):
#        init()
#        p.apply_async(self.conn.commit, callback=self.__commitCallback,error_callback=self.errorc)
        if self.totalEffected!=0:
            thread = threading.Thread(target=self.t)
            thread.start()
        else:
            self.conn.close()

#        p.apply(self.conn.commit)
#        self.conn.close()
#        print('result:' ,result.get())
    def t(self):
        self.conn.commit()
        self.conn.close()

唯一真正需要处理的操作是连接提交(),我使用线程来完成,所以我可以立即返回。我曾经用过Pool.apply\u异步(),但它没有回调,所以我想知道如何让另一个进程调用我,这样我就不必花时间等待receive。你知道吗


Tags: selfcloseexecutesqldefcallbackargsresult