I've explored a few solutions without much success. I have two python processes (created with Popen from subprocess) and one mysql table (called persone) containing one row with two columns: Age:0, id:1. One process selects that row, take it's age and increments it by one. It does that 1000 times. The second does the same thing but decrements it instead. I run each process in parallel.
Theoretically, I would like that at the end, the age remains at zero. The thing is I keep getting random values between 100 and -100 at the end of mymain.py which I guess means there are accesses that are done at the same time, corrupting the database. I was wondering what I was missing?
Here is the code I use to test this:
ajoutAge.py
import MySQLdb as lite
num=1000
connexion = lite.connect(host="localhost", user="root", passwd="123", db="test")
with connexion:
for i in range(num):
cur = connexion.cursor()
cur.execute('start transaction')
cur.execute('select Age from persone where id=1')
age = cur.fetchone()[0]
cur.execute('update persone set Age='+str(age+1)+' where id=1')
# cur.execute('rollback')
cur.execute('commit')
print "ajout Done"
retraitAge.py
import MySQLdb as lite
num=1000
connexion = lite.connect(host="localhost", user="root", passwd="123", db="test")
with connexion:
for i in range(num):
cur = connexion.cursor()
cur.execute('start transaction')
cur.execute('select Age from persone where id=1')
age = cur.fetchone()[0]
cur.execute('update persone set Age='+str(age-1)+' where id=1')
cur.execute('commit')
print "retrait Done"
mymain.py
from subprocess import Popen
a=Popen("python ajoutAge.py", shell=True)
aa=Popen("python ajoutAge.py", shell=True)
b=Popen("python retraitAge.py", shell=True)
bb=Popen("python retraitAge.py", shell=True)
a.communicate()
aa.communicate()
b.communicate()
bb.communicate()
print "Main done"
My table is using InnoDB as the storage engine.