exarkun at intarweb.us
Tue Jan 27 15:21:38 CET 2004
On Tue, Jan 27, 2004 at 09:00:38AM -0500, Bart Nessux wrote:
> Could someone explain the concept of threads and how I might use them in
> Python? I was a math major, not a CS major (theory instead of practice).
> Most of my programming knowledge has grown out of system administration
> and shell scripting, not professional software development.
> How could I make this script threaded, and why should I, how would it
> benefit me? The script already takes up 100% CPU resources, what would
> using threads gain for me:
> #!/usr/bin/python #change this to your Python's path
> def cpu_test():
> x = 0
> while x < 999999999:
> x = x + 1
> print x
> If the above is not suitable for threading, please give me a short
> example of something that is.
On a single CPU machine, threads will never improve the performance of a
CPU-bound task. On multiple CPU machines, threads may improve performance
of CPU-bound tasks, but only in certain very special circumstances.
For more details about this, see http://python.org/doc/api/threads.html
Threads are useful in ways other than exploiting multiple CPUs, though.
They can be used to make blocking APIs appear to be asynchronous, and this
is the prime use of them in Python. For example, DB-API 2.0 specifies an
interface for working with databases, but every method it specifies blocks.
Threads can be used to create a new API wrapped around DB-API which
specifies all the same operations, but with an asynchronous interface,
allowing any regular DB-API 2.0 module to be used without blocking.
This can be useful for working around third-party limitations (it would be
pretty bad if one had to rewrite every DB-API module, just to get an
asynchronous interface). Aside from this, though, threads are only
marginally useful, and can leave to non-deterministic behavior if not used
carefully. Think twice before throwing them into your programs.
More information about the Python-list