多处理python与Sqlite的多个连接

时间:2017-08-10 03:25:57

标签: python sqlite python-multiprocessing

我要做的是激发多个连接到同一个sqlite数据库(因为根据docs不允许共享连接和游标)。

内部gv.py

var = None

内部test.py ...

import multiprocessing as mp
import sqlite3

import gv


def create_conn(dummy):

    conn = None
    print('inside create_conn()')
    print('gv.var =', gv.var)
    try:
        conn = sqlite3.connect(gv.var)
        conn.close()
    except sqlite3.Error:
        print('Error!')


def change_gv_var():
    gv.var = r'D:\test.db'


if __name__ == '__main__':
    print('Start')

    print('Before calling change_gv_var()')
    print('gv.var =', gv.var)
    change_gv_var()
    print('After calling change_gv_var()')
    print('gv.var =', gv.var)

    print('\nCalling pool.map')
    pool = mp.Pool(processes = 4)
    pool.map(create_conn, ['a', 'b', 'c', 'd', 'e'])


    print('Done')

create_conn()函数中,它无法在gv.var中获取multiprocessing.Pool的值,但如果我将其更改为for循环,则没有问题。

输出如下所示。

Start
Before calling change_gv_var()
gv.var = None
After calling change_gv_var()
gv.var = D:\test.db

Calling pool.map
inside create_conn
gv.var = None
inside create_conn
gv.var = None
inside create_conn
gv.var = None
inside create_conn
gv.var = None
inside create_conn
gv.var = None

0 个答案:

没有答案