Threading Example

As mentioned in the handout for Project 3, handling threads is extremely important for both avoiding deadlock and not leaking resources. Below is a link to examples of Project 0 clients in both Python and Java, demonstrating good thread handling in those languages.

These examples are not copy-pasta. They most certainly do not do all the things you will need your reading/writing threads to do in Project 3, and they do not have as much cleanup to do, or as complicated of interactions. However, the fundamental basics of how to properly handle threads are demonstrated: using signals to tell the thread to stop, and using join() to ensure that it did stop, and being able to end threads without exiting the entire program.

Get the code here: Thread Handling Code

Basic Idea

The basic idea is:

A) a thread that spawns threads should not do anything but manage its children threads. This is because handling threads - figuring out when they should be killed, when all the threads that needed a particular resource are dead and that resource can be freed, and when they need to be started - is complicated enough. There is no need to further complicate that code by also trying to make the spawning thread do work while managing other threads. In Project 3 you are going to have a lot of threads being created and dying, and some resources, such as the TCP sockets, will need to be shared and cannot be closed until all threads using them have terminated, so you will want a thread manager thread (or more than one, depending on your architecture).

B) threads need to be able to be signaled to exit. This is because you are going to be spawnin a lot of threads as connections are made, so you will need to be able to cleanly kill those threads as those connections die, without closing the entire program. If you cannot cleanly signal a thread to die, and clean up what it can as it does so, you will probably leak so many resources that your program will not be able to stay up for long.