62 lines
1.3 KiB
C++
62 lines
1.3 KiB
C++
#include "pithread.h"
|
|
|
|
|
|
PIThread::PIThread(bool startNow, int timer_delay) {
|
|
running = lockRun = false;
|
|
priority_ = piNormal;
|
|
timer = timer_delay;
|
|
if (startNow) start(timer_delay);
|
|
}
|
|
|
|
|
|
PIThread::~PIThread() {
|
|
if (!running) return;
|
|
pthread_cancel(thread);
|
|
}
|
|
|
|
|
|
bool PIThread::start(int timer_delay) {
|
|
pthread_attr_t attr;
|
|
terminating = false;
|
|
timer = timer_delay;
|
|
pthread_attr_init(&attr);
|
|
pthread_attr_setschedparam(&attr, &sparam);
|
|
if (pthread_create(&thread, &attr, thread_function, this) == 0) {
|
|
running = true;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
|
|
void * PIThread::thread_function(void * t) {
|
|
PIThread * ct = (PIThread * )t;
|
|
ct->begin();
|
|
while (!ct->terminating) {
|
|
if (ct->lockRun) ct->mutex_.lock();
|
|
ct->run();
|
|
if (ct->lockRun) ct->mutex_.unlock();;
|
|
if (ct->timer > 0) msleep(ct->timer);
|
|
}
|
|
ct->end();
|
|
ct->running = false;
|
|
//cout << "thread " << t << " exiting ... " << endl;
|
|
pthread_exit(0);
|
|
return 0;
|
|
}
|
|
|
|
|
|
void PIThread::setPriority(PIThread::Priority prior) {
|
|
priority_ = prior;
|
|
#if __QNX__ || __WIN32__
|
|
sparam.sched_priority = (int)priority_;
|
|
#else
|
|
sparam.__sched_priority = (int)priority_;
|
|
#endif
|
|
if (!running) return;
|
|
pthread_getschedparam(thread, &policy, &sparam);
|
|
pthread_setschedparam(thread, policy, &sparam);
|
|
}
|
|
|
|
|