python多处理

yuvru6vn  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(431)

我正在尝试插入以更新mysql数据库中非常大的数据值,在同样的尝试中,我试图在进程列表中看到正在做什么!
所以我做了以下脚本:
我有一个修改过的dbmysql,负责连接。一切都很好,除非我使用多进程,如果我使用多进程,我得到了一个错误,在某个时候与“失去连接的数据库”。
剧本是这样的:

  1. from mysql import DB
  2. import multiprocessing
  3. def check writing(db):
  4. result = db.execute("show full processlist").fethcall()
  5. for i in result:
  6. if i['State'] == "updating":
  7. print i['Info']
  8. def main(db):
  9. # some work to create a big list of tuple called tuple
  10. sql = "update `table_name` set `field` = %s where `primary_key_id` = %s"
  11. monitor = multiprocessing.Process(target=check_writing,args=(db,)) # I create the monitor process
  12. monitor.start()
  13. db.execute_many(sql,tuple) # I start to modify table
  14. monitor.terminate()
  15. monitor.join
  16. if __name__ == "__main__"
  17. db = DB(host,user,password,database_name) # this way I create the object connected
  18. main(db)
  19. db.close()

mysql类的一部分是:

  1. class DB:
  2. def __init__(self,host,user,password,db_name)
  3. self.db = MySQLdb.connect(host=host.... etc
  4. def execute_many(self,sql,data):
  5. c = self.db.cursor()
  6. c.executemany(sql, data)
  7. c.close()
  8. self.db.commit()

就像我之前说的,如果我不在 check_writing ,脚本运行良好!
也许有人能告诉我原因是什么,怎样才能克服?而且,我在尝试 threadPool 使用map(或 map_async ). 我是否错过了与 mysql ?

bt1cpqcv

bt1cpqcv1#

有一种更好的方法:
连接器/python连接池:
pooling模块实现池化。
当向请求者提供连接时,池打开许多连接并处理线程安全。
连接池的大小可在池创建时配置。此后无法调整其大小。
可以有多个连接池。例如,这使应用程序能够支持到不同mysql服务器的连接池。
在此处查看文档
我认为你的并行进程正在耗尽你的mysql连接。

相关问题