threads: set up Thread to be freed properly
authorBrian Norris <banorris@uci.edu>
Tue, 24 Apr 2012 03:13:02 +0000 (20:13 -0700)
committerBrian Norris <banorris@uci.edu>
Tue, 24 Apr 2012 03:13:02 +0000 (20:13 -0700)
To ensure that we can free memory properly, set up a destructor and rename
dispose() to complete().

threads.cc
threads.h

index 3af74966469afe1a6897802de9e27c434adf4e76..7d4d22e7aafc68c2cf9e4332e9fceff7465ead46 100644 (file)
@@ -53,11 +53,13 @@ int Thread::swap(Thread *t)
        return swapcontext(&this->context, &t->context);
 }
 
-void Thread::dispose()
+void Thread::complete()
 {
-       DEBUG("completed thread %d\n", thread_current()->get_id());
-       state = THREAD_COMPLETED;
-       stack_free(stack);
+       if (state != THREAD_COMPLETED) {
+               DEBUG("completed thread %d\n", get_id());
+               state = THREAD_COMPLETED;
+               stack_free(stack);
+       }
 }
 
 Thread::Thread(thrd_t *t, void (*func)(), void *a) {
@@ -90,6 +92,12 @@ Thread::Thread(thrd_t *t) {
        model->add_system_thread(this);
 }
 
+Thread::~Thread()
+{
+       complete();
+       model->remove_thread(this);
+}
+
 thread_id_t Thread::get_id()
 {
        return id;
@@ -109,7 +117,7 @@ static int thread_system_next(void)
                        model->scheduler->add_thread(curr);
                else if (curr->get_state() == THREAD_RUNNING)
                        /* Stopped while running; i.e., completed */
-                       curr->dispose();
+                       curr->complete();
                else
                        DEBUG("ERROR: current thread in unexpected state??\n");
        }
index 0c5fdab9d7a2209d4fda10680b0f737b03c657f2..4a8025137013f3c4d9a20c8149cab709f2a1f108 100644 (file)
--- a/threads.h
+++ b/threads.h
@@ -18,8 +18,9 @@ class Thread {
 public:
        Thread(thrd_t *t, void (*func)(), void *a);
        Thread(thrd_t *t);
+       ~Thread();
+       void complete();
        int swap(Thread *t);
-       void dispose();
 
        thread_state get_state() { return state; }
        void set_state(thread_state s) { state = s; }