threading, how to?

Iain King iainking at gmail.com
Fri Apr 21 07:18:32 EDT 2006


akrapus wrote:
> Thanks for reply.
>
> So would it be implemented as follows:
>
> Func 1
> Func 2
> Func 3
>
> Thread for Func 1
> Thread for Func 2
> Thread for Func 3
>
> Cheers
>
> Stevan

Here's how I'm doing it, using the thread module (there's a higher
level class-based module: threading, but I'm more comfortable with the
simple one):

import thread, time

class ThreadDemo:
	def __init__(self):
		self.data = []
		self.lock = thread.allocate_lock()
		self.alive = False


	def Start(self):
		self.alive = True
		thread.start_new_thread(self.Process, (None,))


	def Stop(self):
		self.alive = False


	def Process(self, dummy=None):
		while self.alive:
			self.lock.acquire()
			self.data.sort()
			self.lock.release()
			time.sleep(0.05)


	def Add(self, value):
		self.lock.acquire()
		self.data.append(value)
		self.lock.release()

>>> from ThreadDemo import ThreadDemo
>>> demo = ThreadDemo()
>>> demo.Start()
>>> demo.Add(1)
>>> demo.Add(5)
>>> demo.Add(2)
>>> demo.data
[1, 2, 5]
>>> demo.Add(3)
>>> demo.data
[1, 2, 3, 5]
>>> demo.Stop()
>>> demo.Add(4)
>>> demo.data
[1, 2, 3, 5, 4]

Use the lock whenever you are going to modify data which is shared
between more than one thread.  Using time.sleep stops the thread from
hogging CPU cycles.  You only need to sleep a few milliseconds.  The
thread will clean itself up as soon as it's function (in this case
Process) finishes.  The ugly (None,) tuple in the start_new_thread /
dummy=None Process parameter are because the start_new_thread function
demands a tuple of arguments, even when none are required.
see http://www.python.org/doc/current/lib/module-thread.html for more
info.

Iain




More information about the Python-list mailing list