Home > Fresh News > QThread

QThread

QThread was designed and is intended to be used as an interface or a control point to an operating system thread, not as a place to put code that you want to run in a thread. We object-oriented programmers subclass because we want to extend or specialize the base class functionality. The only valid reasons I can think of for subclassing QThread is to add functionality that QThread doesn’t have, e.g. perhaps providing a pointer to memory to use as the thread’s stack, or possibly adding real-time interfaces/support. Code to download a file, or to query a database, or to do any other kind of processing should not be added to a subclass of QThread; it should be encapsulated in an object of it’s own.

You’re doing it wrong…

// create the producer and consumer and plug them together
Producer producer;
Consumer consumer;

bool bOk = producer.connect(&consumer,
                            SIGNAL(consumed()),
                            SLOT(produce()));
Q_ASSERT(bOk);
bOk = consumer.connect(&producer,
                       SIGNAL(produced(QByteArray *)),
                       SLOT(consume(QByteArray *)));
Q_ASSERT(bOk);

// they both get their own thread
QThread producerThread;
producer.moveToThread(&producerThread);

QThread consumerThread;
consumer.moveToThread(&consumerThread);

// go!
producerThread.start();
consumerThread.start();

Reference: Threading without the headache or QThread’s no longer abstract (see attached file)

  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.