Index: trunk/Ohana/src/opihi/pantasks/pantasks.c.in
===================================================================
--- trunk/Ohana/src/opihi/pantasks/pantasks.c.in	(revision 39457)
+++ trunk/Ohana/src/opihi/pantasks/pantasks.c.in	(revision 41483)
@@ -7,4 +7,7 @@
 # define opihi_rcfile ".pantasksrc"
 
+static pthread_t JobsAndTasksThread;
+static pthread_t controllerThread;
+
 /* program-dependent initialization */
 void program_init (int *argc, char **argv) {
@@ -12,7 +15,4 @@
   OHANA_UNUSED_PARAM(argv);
   
-  pthread_t JobsAndTasksThread;
-  pthread_t controllerThread;
-
   auto_break = TRUE;
 
@@ -67,7 +67,12 @@
 /* add program-dependent exit functions here */
 void cleanup () {
+  // stop the threads before calling the free functions
   QuitKapa ();
   QuitController ();
   ConfigFree ();
+
+  // tell the threads to exit and wait for them to exit
+  QuitJobsAndTasksThread(); pthread_join (JobsAndTasksThread, NULL);
+  QuitControllerThread(); pthread_join (controllerThread, NULL);
 
   FreeBasic ();
