[Tutor] Is generator function similar to multi threading?
ms at cerenity.org
Fri Mar 16 12:25:48 CET 2007
On Friday 16 March 2007 06:52, ammar azif wrote:
> Is generator function similar to multi threading?
Yes, however unlike threads they are more general. They can be used in two
* To generate a sequence of values
* To achieve something similar to multithreading, but without using
operating system threads.
For a tutorial on how to do the latter safely, please take a look at this:
(It's targeted at someone with very basic python skills, since the first
iteration of that tutorial was written for someone who'd learnt python the
We use the latter form extremely heavily on our project to great effect. One
of benefits of using a generator over a thread is that you can (as of python
2.5) kill a generator by sending an exception into it.(though this isn't the
reason we're using them)
As a result combining threading and generators makes sense since you can run a
generator inside a thread, and have a mechanism to kill the thread - you send
an exception into the generator.
That said, the primary intended use of generators *is* to generate values. The
fact they're a restricted co-routine however is incredibly handy. (Because
they can only be single layer, it forces them to be simpler, which in turn
makes them much more reusable)
More information about the Tutor