[Bf-python] a clean python solution for threads, timers and user-events

Theo de Ridder theo.de.ridder at planet.nl
Fri May 23 17:38:45 CEST 2008


A few days ago I had a nice talk with Pablo at the Blender Institute  
where
I  showed him some of my latest work. He made a remark about handling
threads that inspired me to rework my prior solution which I found  
still clumsy.
And yes, there is a elegant solution using only Python.
Here is a template for a module you can start with Alt-P.

Enjoy,
Theo


	import Blender as B
	from threading import Thread, Event

	class Loop (object):
		# simple combined class for msg events and automatic timers
		# see python documentation for semantics
		
		def __init__ (self, handler=None, interval=None):
			self._handler = handler
			self._interval = interval
			self._event = Event()
			self._canceled = False
			self.msg = None
			
		def cancel (self):
			self._canceled = True
			self._event.set()

		def run (self):
			evt = self._event
			while True:
				evt.wait(self._interval)		# timeout when interval != None
				if self._canceled:
					break
				if evt.isSet():
					self._handler(self.msg)  # user msg
					evt.clear()
				else:
					self._handler()	# timeout as automatic timer
		
		def set (self, msg):
			self.msg = msg
			self._event.set()
	
	def timer_handler ():
		# this handler is called each 50 ms
		
	def action_handler ():
		# this handler is called when a 'msg' is set
		
	def main ():
		...
		timerloop = Loop(timer_handler, 0.05)
		thread1 = Thread(target=timerloop.run)
		thread1.start()
		B.thread1 = thread1   # save the thread instance !
		...
		actionloop = Loop(action_handler)
		thread2 = Thread(target=actionloop.run)
		thread2.start()
		B.thread2 = thread2		# save this thread too
		...
			
	main()
	




More information about the Bf-python mailing list