MainThread blocks all others

Bryan Olson fakeaddress at nowhere.org
Tue Aug 9 19:08:23 EDT 2005


Nodir Gulyamov wrote:
> Hello All!
>     I met some strange situation. In MainThread my program wating changes of 
> some variable. This variable should be changed in another thread, but loop, 
> which wait changing variable blocks all other threads.
> Code below:
> 
> class class1:
>     def __init__(self):
>         self.counter = 0
>         result = doSomeJob()
> 
>     def increaseCounter(self):
>         self.counter += 1
> 
>     doSomeJob(self):
>         ##### BLOCKING HERE ###
>         while counter != 1:

Should that be self.counter?

>             pass
>         # ... continue...
> 
> # this class subscribed to some observer which implements thread
> class monitor:
>     def __init__(self, klass):
>         #do some init
>         self.c = klass
>     def update(self):
>         self.c.increaseCounter()
> 
> if __name__ == "__main__":
>     cl1 = class1()
>     m = monitor(cl1)
>     mo = MonitorObserver(m)
> 
> 
> I am very confused how to resolve this problem. Any help will be 
> appreciated.

Make self.counter a semaphore. Untested code:

import threading

class class1:
     def __init__(self):
         self.counter = threading.semaphore(0)
         result = doSomeJob()

     def increaseCounter(self):
         self.counter.release()

     doSomeJob(self):
	# Busy-waiting sucks.
         # while counter != 1:
         #    pass
	self.counter.acquire()
         # ... continue...


-- 
--Bryan




More information about the Python-list mailing list