[Qt-interest] Feeding a QThread from a QList
Mike Blackwell
mkblackwell at gmail.com
Thu Jul 8 18:06:36 CEST 2010
I'm working on a class based on QThread that controls a piece of
hardware which I need to send commands to. The commands are queued in
a QList inside the class. The class run method waits for new commands
to appear in the list and executes them, emitting a signal with the
result. The class looks something like this:
class ComandRunner : public QThread
{
Q_OBJECT
public:
void run(void);
public slot:
int addCommand(Command *cmd);
signals:
void commandComplete(int id);
private:
QList<Command *> m_commands;
QMutex m_cmdAccess;
QSemaphore m_cmdCount;
};
int CommandRunner::addCommand(Command *cmd)
{
m_cmdAccess.lock();
m_commands.append(cmd);
m_cmdCount.release(1);
m_cmdAccess.unlock();
return cmd->m_ID;
}
void CommandRunner::run(void)
{
while (1) {
// Wait for a command to become available
m_cmdCount.acquire(1);
// Grab the fist command in the queue
m_cmdAccess.lock();
Command *cmd = m_commands.takeFirst();
m_cmdAccess.unlock();
// Execute command...
}
}
A couple of questions about this. First, is the right (or a good)
approach? Using both a mutex and a semaphore seems slightly redundant.
Plus, the semaphore is basically mirroring the QList item count. Is
there a canonical way of maintaining a list of events for a thread to
execute? Second, I never call exec() from the run method. Will this
prevent me from using queued signals and slots to to communicate with
other threads? Is there a way to make this work in this framework?
Thanks for any advice!
Mike Blackwell
More information about the Qt-interest-old
mailing list