How should I avoid this race condition?

33 views
Skip to first unread message

Gorgine Hoo

unread,
Dec 8, 2020, 2:23:06 AM12/8/20
to Django REST framework

I have a piece of code like below which is truncated for concise:


bargained_count = BargainLog.objects.filter(bargain_start_log=bargain_start_log).count()    

...
 money = calc_single_bargain_money( bargained_count=bargained_count, ...... ) 
 ...
 BargainLog.objects.create(bargain_start_log=bargain_start_log, money=money, ...)  


bargained_count is a parameter of func calc_single_bargain_money. But, because of the race condition, I am not sure if this is one kind of race condition. I may get bargained_count as same values in high concurrency which will affect the result of calc_single_bargaiN_money. So, how should I avoid it, please give me some advice.

Like in multi threading, I want to add a lock before getting bargained_count and release the lock after creating new BargainLog instance to ensure they are bundled together.

Reply all
Reply to author
Forward
0 new messages