public
Created

  • Download Gist
test_race_condition.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#!/usr/bin/env python
 
import os
import logging
 
from threading import Thread
 
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
 
from optparse import OptionParser
 
# testing with postgresql 9.1
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test',
'USER': 'test',
'PASSWORD': 's3cr3t',
'HOST': '',
'PORT': '',
}
},
INSTALLED_APPS=[
'django.contrib.auth',
],
)
 
from django.db import transaction
from django.contrib.auth.models import User
 
class MyThread(Thread):
 
def __init__(self, username):
super(MyThread, self).__init__(name=username)
self.username = username
 
def run(self):
# passes with get_or_create
instance, created = User.objects.get_or_create(username=self.username)
 
# fails with try get .. except create
#created = False
#try:
#instance = User.objects.get(username=self.username)
#except User.DoesNotExist:
#instance = User.objects.create(username=self.username)
#created = False
print '%s %s' % (instance.id, created)
instance.delete()
return
 
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("--num-threads", type="int", default=5, dest="threads")
options, args = parser.parse_args()
for i in range(options.threads):
thread = MyThread(username="test_user")
thread.start()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.