Starting threads

Mongryong Mongryong at
Wed Jan 29 20:59:16 CET 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):

globalVar = Key

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

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

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