- Main Page
- Classes
- Files

- File List

# OptFrame/Util/Runnable/Runnable.hpp

    00001 #ifndef RUNNABLE_HPP_
    00002 #define RUNNABLE_HPP_
    00003
    00004 #include <pthread.h>
    00005 #include <stdio.h>
    00006 #include <stdlib.h>
    00007 #include <iostream>
    00008
    00009 void * _run(void * arg);
    00010
    00011 class Runnable
    00012 {
    00013 public:
    00014         bool finished_last_job;
    00015
    00016         Runnable()
    00017         {
    00018                 // Initialize and set thread detached attribute
    00019                 pthread_attr_init(&attr);
    00020                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    00021
    00022                 finished_last_job = true;
    00023         };
    00024
    00025         virtual ~Runnable()
    00026         {
    00027                 int e = pthread_attr_destroy(&attr);
    00028
    00029                 if(e!=0)
    00030                         cout << "Error "<<e<<" destroying attr from thread." << endl;
    00031                 /*
    00032                 rc = pthread_join(thread, &status);
    00033                 if (rc)
    00034                 {
    00035                         printf("ERROR; return code from pthread_join() is %d\n", rc);
    00036                         exit(-1);
    00037                 }
    00038                 */
    00039                 //printf("Completed join with thread %d status= %ld\n",t, (long)status);
    00040                 //pthread_exit(NULL);
    00041         }
    00042
    00043         virtual void run() = 0;
    00044
    00045         void start()
    00046         {
    00047                 finished_last_job = false;
    00048                 rc = pthread_create(&thread, &attr, _run, this);
    00049         };
    00050
    00051         void stop()
    00052         {
    00053                 int e = pthread_cancel(thread);
    00054                 if(e!=0)
    00055                         cout << "Error "<<e<<" stopping thread!" << endl;
    00056                 else
    00057                         finished_last_job = true;
    00058         };
    00059
    00060         bool finished()
    00061         {
    00062                 return finished_last_job;
    00063         }
    00064
    00065
    00066 protected:
    00067         pthread_t thread;
    00068         pthread_attr_t attr;
    00069         int rc, t;
    00070         void *status;
    00071 };
    00072
    00073 void * _run(void * arg)
    00074 {
    00075         Runnable * runnable = (Runnable*) arg;
    00076         runnable->run();
    00077         runnable->finished_last_job = true;
    00078         return NULL;
    00079 };
    00080
    00081 #endif /* RUNNABLE_HPP_ */

All Classes Functions