Threads and variable assignment

Gregory Bond gnb at itga.com.au
Mon Apr 11 21:57:50 EDT 2005


I've had a solid hunt through the (2.3) documentation but it seems 
silent on this issue.

I have an problem that would naturally run as 2 threads:  One monitors a 
bunch of asyncrhonous external state and decides if things are "good" or 
"bad".  The second thread processes data, and the processing depends on 
the "good" or "bad" state at the time the data is processed.

Sort of like this:

Thread 1:

global isgood
while 1:
	wait_for_state_change()
	if new_state_is_good():
		isgood = 1
	else:
		isgood = 0

Thread 2:

s = socket(....)
s.connect(...)
f = s.makefile()
while 1:
	l = f.readline()
	if isgood:
		print >> goodfile, l
	else:
		print >> badfile, l

What guarantees (if any!) does Python make about the thread safety of 
this construct?   Is it possible for thread 2 to get an undefined 
variable if it somehow catches the microsecond when isgood is being 
updated by thread 1?



More information about the Python-list mailing list