首页 > 解决方案 > 如何使用 python sqlite3 包在 python 中的不同进程之间共享一个:memory: 数据库

问题描述

场景如下所示,我有很多进程来做 CPU 密集型工作,并且在同一个数据库上只读,我知道缓存和 uri 关键字可以用于 sqlite 在线程之间共享数据库缓存,但是进程之间呢?最好同时适用于linux和windows,谢谢!

def run(self):
    self.phyconn = apsw.Connection(self.fileName)
    self.memconn = apsw.Connection(":memory:")
    try:#backup.__exit__() just make sure copy if finished,not close backup,so with is good,memconn is still exist when out
        with self.memconn.backup("main", self.phyconn, "main") as backup:
            # call with 0 to get the total pages
            backup.step(0)
            total = backup.pagecount

            stepped = 0
            one_percent = total if total < 100 else total // 100
            last_percentage = 0
            while stepped <= total:
                if self.cancel:
                    #self.progressCanceled.emit()
                    self.memconn=None
                    return
                backup.step(one_percent)
                stepped = stepped + one_percent
                stepped_percentage = stepped*100//total
                if stepped_percentage != last_percentage:
                    last_percentage = stepped_percentage
                    #self.progressChanged.emit(stepped_percentage)
                    websocket.UpdateLoadDBProgress(stepped_percentage,self.sid)

标签: pythonsqlitememoryshareapsw

解决方案


这是不可能的。进程的全部意义在于将它们的内存相互隔离。(大多数操作系统允许共享内存,但没有可移植的机制。)

即使有可能,也不会更快,因为 SQLite 和操作系统都会缓存数据。


推荐阅读