谁能告诉我为什么这个Qt代码不会调用定义ASYNC_TIMERS回调时(即m_timer.start从并行线程调用,但插槽从未运行)。显然,这是从并行线程被调用时做没有定义ASYNC_TIMERS,但我想知道如何从并行线程修复它,因为它的工作原理。我尝试了许多在网上找到的东西,包括moveToThread(),调用线程运行时调用exec(),但我对这个问题没有运气?QT的信号/槽和并行线程不玩好起来
干杯
multitimer.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
timer.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();
}
你在同一时间同时使用GLOBAL_TIMERS和ASYNC_TIMERS? – 0xbaadf00d 2011-05-18 06:40:43