Thursday, November 27, 2014

Re: not thread-safe function can break a django application?

Collin, Thanks for the explanation.


Em segunda-feira, 24 de novembro de 2014 20h01min55s UTC-3, Collin Anderson escreveu:


On Saturday, November 22, 2014 4:46:56 AM UTC-5, Fabio Caritas Barrionuevo da Luz wrote:
I was trying to answer a question in a Brazilian forum about django.

one of the proposed solutions utilized the function locale.setlocale() from locale module.

according to the documentation[1] locale.setlocale() function is not thread-safe

the question is: 

not thread-safe function can break a django application?
 Yes

If so, how? 
You can have "race conditions" where _sometimes_ you get unpredictable results.

Which scenario I would have problems? 
One request in one thread could set locale to English and then use the locale, meanwhile, another thread could set it to Spanish and then use the locale. If they did that at the same time, the English request might get the Spanish locale, or the Spanish request might get the English locale.

some easily reproducible example of problems using not thread-safe function?
import threading
state
= {}

def english():
    state
['locale'] = 'english'
   
assert state['locale'] == 'english'

def spanish():
    state
['locale'] = 'spanish'
   
assert state['locale'] == 'spanish'

while 1:
    threading
.Thread(target=english).start()
    threading
.Thread(target=spanish).start()
 
(press ctrl+c to stop)

Also, note that it says "If the locale is not changed thereafter, using multithreading should not cause problems." So, if you only set it once and never change it, you should be fine.

Collin

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/30559735-cf14-4e67-8db5-7587e6a96073%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment