|
Threads and Standard I/O |
Top Previous Next |
|
It is generally a bad idea for the main function of a task to return while any threads it has created are still active if, as in the program above, one of those threads may be using C standard I/O. If this happens, the main function exits, causing the run-time library to attempt to shut down the I/O system and close all open files before some thread which needs to do I/O has finished. This can lead to several obscure errors, most commonly, reports from the server of 'protocol error'. To forestall this possibility, an extra channel has been added in this example from the consumer thread back to the original main thread. It is used purely for synchronisation. When the consumer thread is about to terminate, it sends a dummy message over this channel. The main thread waits for this message before returning. A semaphore could have been used here instead.
Note that the multiplexor example above demonstrates a occasion where it is safe to let main terminate while other threads are active; those threads do not require access to the host for I/O.
When an application has multiple threads that need to continue running when the main function has finished, you should stop the main thread by calling thread_stop. |