Files
pip/pithread.cpp
2011-07-29 08:17:24 +04:00

117 lines
2.4 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 = running = 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;
}
bool PIThread::startOnce() {
pthread_attr_t attr;
terminating = running = false;
pthread_attr_init(&attr);
pthread_attr_setschedparam(&attr, &sparam);
if (pthread_create(&thread, &attr, thread_function_once, this) == 0)
return true;
return false;
}
void * PIThread::thread_function(void * t) {
PIThread * ct = (PIThread * )t;
ct->running = true;
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::thread_function_once(void * t) {
PIThread * ct = (PIThread * )t;
ct->running = true;
ct->begin();
if (ct->lockRun) ct->mutex_.lock();
ct->run();
if (ct->lockRun) ct->mutex_.unlock();
ct->end();
ct->running = false;
//cout << "thread " << t << " exiting ... " << endl;
pthread_exit(0);
return 0;
}
void PIThread::setPriority(PIThread::Priority prior) {
priority_ = prior;
#ifndef LINUX
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);
}
bool PIThread::waitForFinish(int timeout_msecs) {
if (timeout_msecs < 0) {
while (running)
msleep(1);
return true;
}
int cnt = 0;
while (running && cnt < timeout_msecs) {
msleep(1);
++cnt;
}
return cnt < timeout_msecs;
}
bool PIThread::waitForStart(int timeout_msecs) {
if (timeout_msecs < 0) {
while (!running)
msleep(1);
return true;
}
int cnt = 0;
while (!running && cnt < timeout_msecs) {
msleep(1);
++cnt;
}
return cnt < timeout_msecs;
}