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
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
00033
00034
00035
00036
00037
00038
00039
00040
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