有人能告诉我为什么这个 qt 代码在定义 ASYNC_TIMERS 时不会调用回调(即从 pthread 调用 m_timer.start 但插槽从不运行)。显然,这与从 pthread 调用有关,因为它在未定义 ASYNC_TIMERS 时工作,但我想知道如何从 pthread 修复它。我已经尝试了很多在网上找到的东西,包括 moveToThread(),调用线程运行调用 exec(),但我在这个问题上没有运气?
干杯
多定时器.h:
#pragma once
#ifndef MULTI_TIMER_H
#define MULTI_TIMER_H
#include <QThread>
#include <QTimer>
#include <QMutex>
#include <QMap>
#include <QMetaType>
#include <cassert>
class MultiTimer : public QThread
{
Q_OBJECT
public:
typedef void (*multiTimerCallback)(quint32 p_id);
private:
QTimer m_timer;
QMutex m_mutex;
quint32 m_id;
multiTimerCallback m_callback;
void KillTimer(void);
public:
// only TimerFactory is allowed to instantiate MultiTimer
MultiTimer(quint32 p_id, multiTimerCallback p_callback);
~MultiTimer();
enum TTimerType
{
TT_SingleShot, ///< Timer fires only once
TT_Repetitive ///< Timer keeps firing repeatedly until stopped with KillTimer()
};
void SetTimer(quint32 p_delayInMilliseconds, MultiTimer::TTimerType timerType);
private slots:
void Update(void);
};
#endif
计时器.cpp:
#include <QtCore/QCoreApplication>
#include "multitimer.h"
#include <stdio.h>
//--------------------------------------------------------------------------------------------------
void MultiTimer::SetTimer(quint32 p_delayInMilliseconds, MultiTimer::TTimerType timerType)
{
QMutexLocker locker(&m_mutex);
m_timer.setSingleShot(TT_SingleShot == timerType ? true : false);
m_timer.start(p_delayInMilliseconds);
//QTimer::singleShot(p_delayInMilliseconds, this,SLOT(Update()));
}
void MultiTimer::KillTimer(void)
{
QMutexLocker locker(&m_mutex);
m_timer.stop();
}
void MultiTimer::Update(void)
{
QMutexLocker locker(&m_mutex);
if (NULL != m_callback)
m_callback(m_id);
}
MultiTimer::MultiTimer(quint32 p_id, multiTimerCallback p_callback)
: m_id(p_id)
, m_callback(p_callback)
{
bool isConnected = true;
isConnected &= this->connect(&this->m_timer, SIGNAL(timeout()), this, SLOT(Update()), Qt::QueuedConnection);
assert(isConnected);
//this->start();
}
MultiTimer::~MultiTimer()
{
KillTimer();
wait();
}
//--------------------------------------------------------------------------------------------------
#define ASYNC_TIMERS
#define GLOBAL_TIMERS
void Callback(quint32 p_id)
{
printf("Got timered by timer %d.\n", p_id);
}
MultiTimer *mt;
void StartTimers(void)
{
#ifndef GLOBAL_TIMERS
mt = new MultiTimer(1, Callback);
#endif
mt->SetTimer(1000, MultiTimer::TT_SingleShot);
}
#ifdef ASYNC_TIMERS
pthread_t AsyncTaskThread;
void *ProcessAsyncTasks(void */*ptr*/)
{
StartTimers();
return NULL;
}
#endif
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
#ifdef GLOBAL_TIMERS
mt = new MultiTimer(1, Callback);
#endif
#ifdef ASYNC_TIMERS
pthread_create(&AsyncTaskThread, NULL, &ProcessAsyncTasks, NULL);
#else
StartTimers();
#endif
return a.exec();
}