#ifndef TIMEOUTCALLBACK_H
#define TIMEOUTCALLBACK_H
#include <stdio.h>
#include <string>
class TimeoutCallback
{
public:
virtual void timeout(std::string) = 0;
};
#endif // TIMEOUTCALLBACK_H
#ifndef TIMEOUTTHREAD_H
#define TIMEOUTTHREAD_H
#include "timeoutcallback.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
struct TimerControl
{
std::string stringName;
bool isStop ;
int interval;
TimeoutCallback * ptr;
TimerControl()
{
stringName = "";
isStop = false;
interval = 1000;
ptr = NULL;
}
};
class TimeoutThread{
public:
TimeoutThread();
~TimeoutThread();
void startTimer(int interval,std::string timerName,TimeoutCallback *pCallback);
void stopTimer();
bool isActive();
protected:
void run();
private:
bool m_bStop = true;
int m_msleepValue;
std::string m_timerName;
TimerControl *m_timerControl;
};
#endif // TIMEOUTTHREAD_H
//cpp
#include "timeoutthread.h"
void *thread1(void *arg)
{
TimerControl * callBackControl= (TimerControl *)arg;
while(!callBackControl->isStop)
{
usleep(callBackControl->interval);
callBackControl->ptr->timeout(callBackControl->stringName);
}
}
TimeoutThread::TimeoutThread()
{
m_timerControl = new TimerControl();
}
TimeoutThread::~TimeoutThread()
{
delete m_timerControl;
}
void TimeoutThread::startTimer(int interval,std::string timerName,TimeoutCallback *pCallback)
{
if(isActive() )
{
return;
}
m_timerControl->ptr = pCallback;
m_timerControl->stringName = timerName;
m_timerControl->isStop = false;
m_timerControl->interval = interval * 1000;
m_msleepValue = interval;
// start();
run();
}
void TimeoutThread::stopTimer()
{
m_timerControl->isStop = true;
}
bool TimeoutThread::isActive()
{
// return isRunning();
if(m_timerControl->ptr == NULL)
return false;
return !m_timerControl->isStop;
}
void TimeoutThread::run()
{
printf("Enter main function.\n");
pthread_t tid1;
int err1 = 0;
err1 = pthread_create(&tid1, NULL, thread1, m_timerControl);
// if(err1 != 0)
// printf("%s: %d\n", __func__, strerror(err1));
//========================================
}
//使用需要继承TimeoutCallback
#ifndef TEST_H
#define TEST_H
#include <QObject>
#include "timeoutcallback.h"
#include "timeoutthread.h"
class Test : public QObject,TimeoutCallback
{
Q_OBJECT
public:
explicit Test(QObject *parent = 0);
void timeout(std::string);
TimeoutThread *timer;
TimeoutThread *timer1;
signals:
public slots:
};
#endif // TEST_H
#include "test.h"
#include <QDebug>
Test::Test(QObject *parent) : QObject(parent)
{
timer = new TimeoutThread;
timer->startTimer(1000,"name1",this);
timer1 = new TimeoutThread;
timer1->startTimer(1000,"name2",this);
}
void Test::timeout(std::string str)
{
qDebug()<<QString::fromStdString(str);
}