I am struggling with multi-threading with a connection pool on Django.
I know python threading has GIL issue but I thought python threading is enough to improve performance if the most of the work are DB I/O.
First all I tried to implement a small code to prove my thought.
Simply explaining, the code uses threadPool.apply_async() with a DB connection pool set by CONN_MAX_AGE in settings.py.
With the code, I repeat controlling the number of threads for the worker thread.
from multiprocessing import pool
from threadPoolTestWithDB_IO import models
from django.db import transaction
import django
import datetime
import logging
import g2sType
def addEgm(pre, id_):
"""
@summary: This function only inserts a bundle of records tied by a foreign key
"""
try:
with transaction.atomic():
egmId = pre + "_" + str(id_)
egm = models.G2sEgm(egmId=egmId, egmLocation="localhost")
egm.save()
device = models.Device(egm=egm,
deviceId=1,
deviceClass=g2sType.t_deviceClass.G2S_eventHandler,
deviceActive=True)
device.save()
models.EventHandlerProfile(device=device, queueBehavior="a").save()
models.EventHandlerStatus(device=device).save()
for i2 in range(1, 200):
models.EventReportData(device=device,
deviceClass=g2sType.t_deviceClass.G2S_communications,
deviceId=1,
eventCode="TEST",
eventText="",
eventId=i2,
transactionId=0
).save()
print "Done %d" % id_
except Exception as e:
logging.root.exception(e)
if __name__ == "__main__":
django.setup()
logging.basicConfig()
print "Start test"
tPool = pool.ThreadPool(processes=1) #Set the number of processes
s = datetime.datetime.now()
for i in range(100): #Set the number of record bundles
tPool.apply_async(func=addEgm, args=("a", i))
print "Wait worker processes"
tPool.close()
tPool.join()
e = datetime.datetime.now()
print "End test"
print "Time Measurement : %s" % (e-s,)
models.G2sEgm.objects.all().delete() #remove all records inserted while the test
--------------------------
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'orcl',
'USER': 'test',
'PASSWORD': '1123',
'HOST': '192.168.0.90',
'PORT': '1521',
'CONN_MAX_AGE': 100,
'OPTIONS': {'threaded': True}
}
}
However, the result came out as they don't have any big difference between 1 thread worker and multi-thread works.
For example, It takes 30.6 sec with 10 threads and takes 30.4 sec with 1 thread.
What did I go wrong?