The previous post gives a good description of what multithreading is, but I thought I'd offer a small example of why it can be useful.

Consider, a program that listens for packets on an UDP socket, performs some operation on the input, and then spits the result back to the sender. I would code this using several threads:

  • One thread that waits for incoming packets and puts each packet in an input (FIFO) queue, then goes back to wait for the next packet.
  • One thread that picks packets out of the input queue, performs the operation, then puts the result in an output (also FIFO) queue. Actually, you could have several threads working in parallell doing this, which would be even more efficient if the operation involves any kind of blocking I/O (such as database access).
  • One thread that takes items from the output queue and sends each packet back to the original sender.
Doing things this is far better than having a single thread that does everything; listening for input, doing calculation and writing output. In that case, every request would have to wait until the previous one had been processed, which is fine if we only get few requests, but slows everything down when traffic goes up. Eventually, the network layer will start dropping incoming packets since its inpur buffer fills up. If there is a thread that reads every packet as it arrives we can avoid that.