Python Examples on Threading
Posted 14 Feb 2004 by herman
Some examples of threading used in class on the 13th and the 16th.
Here are examples used in class for you to examine, modify (insert print
statements if you run them and wonder what is happening), and use as
examples for your own programming.
- thdemo.py is a simple demonstration of the
threading module, documented in Chapter 14. The program
uses both a lock and semaphore to control concurrency.
- badthread.py is an incorrect program;
sometimes it will produce a wrong result because the shared
variable is accessed without locking.
- quick_tcp_server.py is a very simple
example of a threaded TCP server (but
possibly incorrect). As requested, I made an untested but commented
version as well: quick_tcp_serverC.py.
- threading_tcp_server1.py shows how the
Queue module can be used in place of locking for management
of concurrency. The example demonstrates a multithreaded
TCP server (an improvement over tcp_server.py).
In fact, there exist classes for threading TCP servers and
clients (mentioned on page 439) that are probably better
to use than the technique of this example, but it is nice
to see explicitly how the threading is managed first.
Also, as requested, I made an (untested) but commented version of
the server in threading_tcp_server1C.py.
- cat.py is an elementary example to illustrate
reading a file and getting input from the keyboard.
Pages 444-445 in the Nutshell book document the
select module, which can be used to manage concurrent
client access to a server without using any
thread package.
An example presented in class on the 18th covers
this technique: select_tcp_server.py
shows a simple tcp server for multiple clients.
|