If you’ve come to Python from another language (certainly a low level language) then you know that threading is hard. You have a mutex or a semaphore which may be achievable with the synchronized command if the language supports it.

So it should come as no surprise to find in Python you initialize a Thread class with the function you want to run (myfunc in the example below) and start it.

t = threading.Thread(target=myfunc)

I could put a fully working example in with a few more lines but SaltyCrane already has a simple Threading example on his blog which I cannot beat for clarity.

The problem with this simplistic method is there is no way to interact with the thread. Fine if you want to split out a long running I/O operation or finite background task but what if you need to stop the thread or query its status. You could work around these by passing in a mutable object but really you want to create your own class.

In the Thread class, when you call start it passes control over to the run method to actually execute your function. So your class just needs to override this run method. You will probably want to override the __init__ method as well, in which case don’t forget to call the parent initialization.

To demonstrate I have created a simple threading example. You initialise the class with a name and the number of seconds to sleep and it just writes the name to the console then sleeps for the specified time. The testing code creates 5 classes with different names / sleep times and then starts them running for 5 minutes so you can see the different output then stops them.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s