Starting threads

Mongryong Mongryong at sympatico.ca
Wed Jan 29 14:59:16 EST 2003


If you really do need globals variables when using threads, there's a
concept know as thread "keys".  Basically, the globally variable
"changes" for each thread.

Here's a simple implementation of a thread key:

import thread
class Key:
	def __init__(self):
		self.value = {}

	def set(self, value):
		self.value[thread.get_ident()] = value

	def get(self):
		self.value[thread.get_ident()]

globalVar = Key

class MyThread(Thread):
	def __init__(self, name):
		globalVar.set(name)
	def getName(self):
		return globalVar.get()

for a in ["comp1", "comp2"]:
	thread = MyThread(a)
	thread.start()

Of course, this is a contrive example.  In this simple example, you're
probably better to use a member variable for each thread.  But thread
keys might be useful for other things where having a global variable is
a simpler solution.






More information about the Python-list mailing list