Threads and Semaphores: 4.4 Using Multiple Threads: When a Thread Is Finished

Up: GEOS SDK TechDocs | Up | Prev: 4.3 Handling Errors in a Thread | Next: 5 Synchronizing Threads
ThreadDestroy()

Whenever an application creates an additional thread with MSG_PROCESS_CREATE_EVENT_THREAD or ThreadCreate() , it must be sure that the thread exits when it is finished. Simply exiting the application may not eliminate any additional threads, and these threads can cause GEOS to hang when shutting down the system.

When a thread exits, it should first release any semaphores or thread locks it has locked and free any memory or other resources that are no longer needed. Resources in memory do not have to be freed in the same thread that allocated them, but you should be sure that they are freed before the application exits.

A procedural thread exits by calling ThreadDestroy() with three arguments: an error code, an optr, and a word of data. When the thread exits, it sends (as its last act) a MSG_PROCESS_NOTIFY_THREAD_EXIT to the application's primary thread and a MSG_META_ACK to the object descriptor passed. (ThreadDestroy()'s word of data argument will be passed as the lower word of MSG_META_ACK's optr argument.) Each message has the error code as an argument. In designing a multi-threaded application, you can create methods for MSG_PROCESS_NOTIFY_THREAD_EXIT (in your primary thread's class) or MSG_META_ACK (in any class) for communication among threads, and you may use the error code for any data you choose. The convention is that an error code of zero represents successful completion of a thread's task.

An event-driven thread should not call ThreadDestroy() directly because its event queue must be removed from the system cleanly. Instead, send a MSG_META_DETACH to the thread, passing the same arguments as for ThreadDestroy() . The handler for MSG_META_DETACH in MetaClass cleanly removes the event queue and terminates the thread, sending the same messages as described above. You may write a special handler for MSG_META_DETACH when you subclass ProcessClass , but be sure to end the handler with @callsuper() so the thread exits properly.


Up: GEOS SDK TechDocs | Up | Prev: 4.3 Handling Errors in a Thread | Next: 5 Synchronizing Threads