I have a simple function that writes the output of some calculations in a sqlite table. I would like to use this function in parallel using multi-processing in Python. My specific question is how to avoid conflict when each process tries to write its result into the same table? Running the code gives me this error: sqlite3.OperationalError: database is locked.
import sqlite3
from multiprocessing import Pool
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("CREATE TABLE table_1 (id int,output int)")
def write_to_file(a_tuple):
index = a_tuple[0]
input = a_tuple[1]
output = input + 1
c.execute('INSERT INTO table_1 (id, output)' 'VALUES (?,?)', (index,output))
if __name__ == "__main__":
p = Pool()
results = p.map(write_to_file, [(1,10),(2,11),(3,13),(4,14)])
p.close()
p.join()
Traceback (most recent call last):
sqlite3.OperationalError: database is locked
Using a Pool is a good idea.
I see three possible solutions to this problem.
First, instead of having the pool worker trying to insert data into the database, let the worker return the data to the parent process.
In the parent process, use imap_unordered instead of map.
This is an iterable that starts providing values as soon as they become available. The parent can than insert the data into the database.
This will serialize the access to the database, preventing the problem.
This solution would be preferred if the data to be inserted into the database is relatively small, but updates happen very often. So if it takes the same or more time to update the database than to calculate the data.
Second, you could use a Lock. A worker should then
acquire the lock,
open the database,
insert the values,
close the database,
release the lock.
This will avoid the overhead of sending the data to the parent process. But instead you may have workers stalling waiting to write their data into a database.
This would be a preferred solution if the amount of data to be inserted is large but it takes much longer to calculate the data than to insert it into the database.
Third, you could have each worker write to its own database, and merge them afterwards. You can do this directly in sqlite or even in Python. Although with a large amount of data I'm not sure if the latter has advantages.
The database is locked to protect your data from corruption.
I believe you cannot have many processes accessing the same database at the same time, at least NOT with
conn = sqlite3.connect('test.db')
c = conn.cursor()
If each process must access the database, you should consider closing at least the cursor object c (and, perhaps less strictly, the connect object conn) within each process and reopen it when the process needs it again. Somehow, the other processes need to wait for the current one to release the lock before another process can acquire the lock. (There are many ways to achieved the waiting).
Setting the isolation_level to 'EXCLUSIVE' fixed it for me:
conn = sqlite3.connect('test.db', isolation_level='EXCLUSIVE')
Related
I am using Python 3.6.8 and have a function that needs to run 77 times. I am passing in data that is pulling data out of PostgreSQL and doing a statistical analysis and then putting back into the database. I can only run 3 processes at the same time due to one at a time takes way to long (about 10 min for each function call) and me only being able to have 3 DB connections open at one time. I am trying to use the Poll library of Multiprocessing and it is trying to start all of them at once which is causing a too many connections error. Am i using the poll method correctly, if not what should i use to limit to ONLY 3 functions starting and finishing at the same time.
def AnalysisOf3Years(data):
FUNCTION RAN HERE
######START OF THE PROGRAM######
print("StartTime ((FINAL 77)): ", datetime.now())
con = psycopg2.connect(host="XXX.XXX.XXX.XXX", port="XXXX", user="USERNAME", password="PASSWORD", dbname="DATABASE")
cur = con.cursor()
date = datetime.today()
cur.execute("SELECT Value FROM table")
Array = cur.fetchall()
Data = []
con.close()
for value in Array:
Data.append([value,date])
p = Pool(3)
p.map(AnalysisOf3Years,Data)
print("EndTime ((FINAL 77)): ", datetime.now())
It appears you only briefly need your database connection, with the bulk on the script's time spent processing the data. If this is the case you may wish to pull the data out once and then write the data to disk. You can then load this data fresh from disk in each new instance of your program, without having to worry about your connection limit to the database.
If you want to look into connection pooling, you way wish to use pgbouncer. This is a separate program that sits between your main program and the database, pooling the number of connections you give it. You are then free to write your script as a single-threaded program, and you can spawn as many instances as your machine can cope with.
It's hard to tell why your program is misbehaving as the indentation is appears to be wrong. But at a guess it would seem like you do not create an use your pool in side a __main__ guard. Which, on certain OSes could lead to all sorts of weird issues.
You would expect well behaving code to look something like:
from multiprocessing import Pool
def double(x):
return x * 2
if __name__ == '__main__':
# means pool only gets created in the main parent process and not in the child pool processes
with Pool(3) as pool:
result = pool.map(double, range(5))
assert result == [0, 2, 4, 6, 8, 10]
You can use SQLAlchemy Python package that has database connection pooling as a standard functionality.
It does work with Postgres and many other database backends.
engine = create_engine('postgresql://me#localhost/mydb',
pool_size=3, max_overflow=0)
pool_size max number of connections to the database. You can set it to 3.
This page has some examples how to use that with Postgres -
https://docs.sqlalchemy.org/en/13/core/pooling.html
Based on your use case you might be also interested in
SingletonThreadPool
https://docs.sqlalchemy.org/en/13/core/pooling.html#sqlalchemy.pool.SingletonThreadPool
A Pool that maintains one connection per thread.
I have a function called connection which connects to the SQL databases. It can be simplified as:
import psycopg2 as pg
def connection():
_conn_DB = pg.connect(dbname="h2", user="h2naya", host=h2_IP, password=DB_PW)
_conn_DB.set_client_encoding('UTF8')
_conn_ML = pg.connect(dbname="postgres", user="h2naya", host="localhost", password=ML_PW)
_conn_ML.set_client_encoding('UTF8')
return {"db": _conn_DB, "ml": _conn_ML}
Now I am trying to get data within a 7-day period starting from a specified date, so I create another function:
import pandas as pd
conns = connection()
def get_latest_7d(date_string):
with conns["db"] as conn:
# date_string is formatted in my_sql in the real life
fasting_bg_latest_7d = pd.read_sql(my_sql, conn)
return fasting_bg_latest_7d
Now I can map get_latest_7d with a list of date strings, e.g. map(get_latest_7d, ["2018-07-01", "2018-07-02", "2018-07-03"]). It works.
As the list of date strings is really long, I'd like tool use multiprocessing.Pool.map to accelerate the procedure. However, the codes below give me InterfaceError: connection already closed:
from multiprocessing import Pool
with Pool() as p:
results = p.map(get_latest_7d, ["2018-07-01", "2018-07-02", "2018-07-03"])
I tried different ways and found the only working one is moving the line conns = connection() inside get_latest_7d, and not closing the connections before returning the data frame. By saying "closing the connections" I mean:
for conn_val in conns.values():
conn_val.close()
It seems that I need to create connections for each process, and I am not allowed to close the connections before the process ends. I am curious about:
Why can't the connection be shared across the processes?
Why does closing a connection in one process affect other processes?
Is there any better practice for my purpose?
PS: It seems to be recommended to build connections in each process but I am not sure that I fully understand.
I've created a quite simple script that works with multiprocessing and SQL. The aim of this exercise is to obtain the lowest time of execution :
def Query(Query):
conn = sqlite3.connect("DB.db")
cur = conn.cursor()
cur.execute(Query)
cur.close()
conn.close()
return
if __name__ == '__main__':
conn = sqlite3.connect("DB.db")
cur = conn.cursor()
start = time.time()
curOperations.execute(QUERY)
curOperations.execute(QUERY)
curOperations.execute(QUERY)
end = time.time()
TIME1 = end - start
cur.execute('PRAGMA journal_mode=wal')
conn.commit()
start = time.time()
pool = Pool(processes=2)
pool.imap(Query,[QUERY, QUERY, QUERY])
pool.close()
pool.join()
end = time.time()
TIME2 = end - start
cur.close()
conn.close()
The average result for TIME1 after 20 executions is 13.43 and for TIME2, 10.39.
Shouldn't it be lower than that ?! am I doing something wrong ?
For my answer, I will assume that your query only reads things from the database.
Before you try to make something faster, you need to know what exactly is preventing the process from being faster.
Not all speed problems are amendable to improvement by multiprocessing!
So what you really need to do is profile the application to see where it spends its time.
Since SQLite does caching of queries, I would suggest timing each execution of the query in the single process separately.
I would suspect that the first query takes longer than the following ones.
Also consider the overhead in the multiprocessing case. The query has to be pickled and sent to the worker process via IPC. Then each worker has to create a connection and cursor and close them afterwards. In a real world situation, your query function would have done something with the data, e.g. return it to the master process which also requires pickling it and sending it via IPC.
Since all workers access the same database, at some point the reading from the database will become the bottleneck.
If you query modifies the database, access will be serialized anyway to prevent coruption.
(Please note: There is a question called "SQLite3 and Multiprocessing" but that question is actually about multithreading and so is the accepted answer, this isn't a duplicate)
I'm implementing a multiprocess script, each process will need to write some results in an sqlite table. My program keeps crashing with database is locked (with sqlite only one DB modification is allowed at a time).
Here's an example of what I have:
def scan(n):
n = n + 1 # Some calculation
cur.execute(" \
INSERT INTO hello \
(n) \
VALUES ('"+n+"') \
")
con.commit()
con.close()
return True
if __name__ == '__main__':
pool = Pool(processes=int(sys.argv[1]))
for status in pool.imap_unordered(scan, range(0,9999)):
if status:
print "ok"
pool.close()
I've tried using a lock by declaring a lock in the main and using it as a global in scan(), but it didn't stop me getting the database is locked.
What is the proper way of making sure only one INSERT statement will get issued at the same time in a multiprocess Python script?
EDIT:
I'm running on a Debian-based Linux.
This will happen if the write lock can't be grabbed within (by default) a 5-second timeout. In general, make sure your code COMMITs its transactions with sufficient frequency, thereby releasing the lock and letting other processes have a chance to grab it. If you want to wait for longer, you can do that:
db = sqlite.connect(filename, timeout=30.0)
...waits for 30 seconds.
I have some script which use multiprocessing module, and Django ORM.
Scenario is quite simple:
get data,
create n processes and assing one part of data to each process,
do something,
save into DB with Django ORM.
Well, in step 4 I have problem that Django don't save all data in DB. Function which prepare data are correct and checked, but I don't know where is problem with Django. Before processes are created, old connection is closed, so that each process can have his own connection.
Is there some problem with Django and multiprocessing, or number of maximum connections (I use 4 process max)?
Example code:
connection.close()
#part where I call function "fun", and sending data
p = Process(target=fun, args=(i, data,)
def fun(i, data):
result_1 = some_other_fun(data) #this is list
result_2 = some_other_fun2(data) #this is model specified in models.py
save_data(result_1, result_2)
def save_data(res1, res2):
for row in res1:
res1.fk_to_another_table = res2
res1.some_info = func()
res1.save()
Long story short. If I call save_data from Process, save() method doesn't save row in table. If that method is called without using Process (just normal call of script), everything is ok.