• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Qt Framework Events Signals Threads
 

Qt Framework Events Signals Threads

on

  • 16,407 views

Qt Framework Events Signals Threads

Qt Framework Events Signals Threads

Statistics

Views

Total Views
16,407
Views on SlideShare
16,307
Embed Views
100

Actions

Likes
1
Downloads
152
Comments
0

6 Embeds 100

http://www.slideshare.net 73
http://www.linux.rk.edu.pl 20
http://www.linkedin.com 4
http://www.lmodules.com 1
http://webcache.googleusercontent.com 1
http://www.docshut.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Qt Framework Events Signals Threads Qt Framework Events Signals Threads Presentation Transcript

    • Threads, Events, Signals/Slots
      Multithreaded Programming in QT
    • Content
      Threading in QT
      QT Reentrancy vs QT ThreadSafe
      GUI and Non-GUI Threads
      Events and Event Loop
      Mechanism, restriction of using Events
      Integration in S60
      Signals and Slots
      API and usage
      Implementation details
    • Threading in QT
      QT framework provide APIs “similar” to Posix
      Base class is QThread, derive a class from this and implement run()
      Important thread APIs are
      QThread::Run() – Starting point of thread, virtual function to be overridden by Apps
      QThread::Start() – Begins execution of thread by calling run()
      QThread::Stop() – For terminating thread
      QThread::Wait() – For waiting for thread completion
      Objects in QT are associated with the thread they are created in
      There is an API to transfer the Ownership of on Object from one thread to another
      Imp: Ownership of QThread is with thread which created the object, typically Main Thread.
      Typical thread will create an Object associated to the thread in Run() and start event loop by calling QThread::exec()
    • Threading in QT contd..
      QT Reentrant methods
      Methods of class can be called simultaneously by different threads as long as they are invoked on different objects
      That is reentrant methods do not operate on global or static data
      However these methods are not atomic and hence not thread safe if invoked on same object
      QT Thread safe methods
      A thread-safe function can be called simultaneously from multiple threads, even when the invocations use shared data, because all references to the shared data are serialized
      Higher degree of guarantee
      These methods are reentrant and atomic
      QT provide Thread safe synchronization APIs
      Like QMutex , Qsemaphore etc.. (More on Next slide)
      Using these user application can make explicitly make reentrant API thread safe
    • Threading in QT contd..
      Qtprovides all Posix compatible Synchronization APIs
      Like mutex, semaphore, readers writers lock, conditional variables
      Qtincludes the following thread classes:
      QThreadprovides the means to start a new thread.
      QThreadStorageprovides per-thread data storage.
      QMutexprovides a mutual exclusion lock, or mutex.
      QMutexLockeris a convenience class that automatically locks and unlocks a QMutex.
      QReadWriteLockprovides a lock that allows simultaneous read access.
      QReadLockerand QWriteLocker are convenience classes that automatically lock and unlock a QReadWriteLock.
      QSemaphoreprovides an integer semaphore (a generalization of a mutex).
      QWaitConditionprovides a way for threads to go to sleep until woken up by another thread.
    • Threading in QT contd..
      In QT UI operations are allowed only from Main UI thread
      QCoreApplication::exec() should be called from main thread
      QWidget and all its subclasses, are not reentrant. They can only be used from the main thread. Objects of Classes derived from QWidget can only be created in Main UI thread
      Similar restrictions are there in S60 also RWindow handle and API using RWindow handle can be accessed from main UI thread only
    • Events and Event Loop in QT
      QT is designed as an Event based non preemptive scheduling model
      Each thread executes an event loop
      Main UI thread execute Application event loop (Q[core]Application::exec)
      Auxiliary Threads execute thread specific event loop (QThread::exec())
      Event are targeted towards specific QObjects and handled by event handlers
      Event handlers run till completion for event loop
      QT QObject implements composite pattern
      That is QObjects can have a parent and a collection of children
      Events are propagated to parents if no handled by child
      Child can ignore events by ignore() method or can accept() and stop propagation
    • Events and Event Loop in QT contd..
      QT guarantees that an Object will receive events in its own thread
      A QObject can “SendEvent()” synchronously to the objects of its own thread, i.eSendEvent() can be used for Intra thread communication only
      QObject can “postEvent()” asynchronously to objects in other thread
      QObject can ensure all posted event of on Object are delivered synchronously using “SendPostedEvent()” this again can be done for Objects of its own thread
      QT Events
      System events For Windowing system, Key events , Mouse events
      Some of these events collate e.g. Multiple Paint events in the Queue are collated and delivered as single Paint event with union of all dirty regions.
      Application can define its own Custom events
      Events can be prioritized
    • Events and Event Loop in QT contd..
      Qtoffers five levels at which events can be processed and filtered:
      We can reimplement a specific event handler
      Reimplementingevent handlers such as mousePressEvent(), keyPressEvent(), and paintEvent() is by far the most common way to process events. We have already seen many examples of this.
      We can reimplementQObject::event()
      By reimplementing the event() function, we can process events before they reach the specific event handlers. This approach is mostly needed to override the default meaning of the Tab key, as shown earlier (p. 168). This is also used to handle rare types of events for which no specific event handler exists (e.g., QEvent::HoverEnter). When we reimplement event(), we must call the base class's event() function for handling the cases we don't explicitly handle.
      We can install an event filter on a single QObject.
      Once an object has been registered using installEventFilter(), all the events for the target object are first sent to the monitoring object's eventFilter() function. If multiple event filters are installed on the same object, the filters are activated in turn, from the most recently installed back to the first installed.
      We can install an event filter on the QApplication object.
      Once an event filter has been registered for qApp (the unique QApplication object), every event for every object in the application is sent to the eventFilter() function before it is sent to any other event filter. This approach is mostly useful for debugging. It can also be used to handle mouse events sent to disabled widgets, which QApplication normally discards.
      We can subclass QApplication and reimplement notify().
      Qtcalls QApplication::notify() to send out an event. Reimplementing this function is the only way to get all the events, before any event filters get the opportunity to look at them. Event filters are generally more useful, because there can be any number of concurrent event filters, but only one notify() function.
    • Signals and Slots
      Unique inter-object communication mechanism, provides
      Type-safe callback between objects
      The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.)
      Facilitates loose coupling / encapsulation
      Sender and receiver does not ”know about” each other
      1-to-many, many-to-1 communication between objects
      Fully Object-oriented
      Signals: emit events
      declare as signals, otherwise normal member functions
      You don't implement them. Rather, you send them with the keyword emit
      E.g. emit sliderChanged(5)
      Slots: receive and handle events
      Normal member functions declared as slots
      Connect: must connect signals to slots
      QObject::connect( mymenu, SIGNAL(activated(int)), myobject, SLOT(slotDoMenuFunction(int)) );
    • Signals and Slots Contd..
      New C++ Syntax for defining Signals/Slots
      class myClass : public QObject {
      Q_OBJECT //required macro, no semicolon

      signals:
      void somethingHappened();

      public slots:
      void slotDoSomething();

      private slots:
      void slotDoSomethingInternal();

      };
      moc: meta object compiler (preprocessor) converts these new keywords to real C++
    • Signals and Slots contd..
      One signal can be connected to many slots:
      connect(slider, SIGNAL(valueChanged(int)), spinBox, SLOT(setValue(int)));
      connect(slider, SIGNAL(valueChanged(int)), this, SLOT(updateStatusBarIndicator(int)));
      When the signal is emitted, the slots are called one after the other, in an unspecified order.
      Many signals can be connected to the same slot:
      connect(lcd, SIGNAL(overflow()), this, SLOT(handleMathError()));
      connect(calculator, SIGNAL(divisionByZero()), this, SLOT(handleMathError()));
      When either signal is emitted, the slot is called.
      A signal can be connected to another signal:
      connect(lineEdit, SIGNAL(textChanged(constQString &)), this, SIGNAL(updateRecord(constQString &)));
      When the first signal is emitted, the second signal is emitted as well. Apart from that, signal–signal connections are indistinguishable from signal–slot connections.
      Connections can be removed:
      disconnect(lcd, SIGNAL(overflow()), this, SLOT(handleMathError()));
      This is rarely needed, because Qt automatically removes all connections involving an object when that object is deleted.
    • Signals and Slots Contd..
      Qt supports four types of signal-slot connections:
      With direct connections, the slot gets called immediately when the signal is emitted. The slot is executed in the thread that emitted the signal (which is not necessarily the thread where the receiver object lives).
      With queued connections, the slot is invoked when control returns to the event loop of the thread to which the object belongs. The slot is executed in the thread where the receiver object lives.
      With auto connections (the default), the behavior is the same as with direct connections if the signal is emitted in the thread where the receiver lives; otherwise, the behavior is that of a queued connection.
      With blocking queued connection, the behavior is the same as with queued connection, except that the current thread blocks until the slot has been delivered. This connection type should only be used for receivers in a different thread. Note that misuse of this type can lead to dead locks in your application.
    • Signals and Slot Contd..
      Using direct connections when the sender and receiver live in different threads is unsafe if an event loop is running in the receiver's thread, we need to use insure synchronization explicitly.
      For Queued connections or for the AUTO connection when receiving thread lives on a different thread.
      QT code internally sends event called QMetaCallEvent.
      This event is handled by the QT event loop and it in turn calls qt_metacallwhich finally calls the slot function
      Argument of signals are allocated and copied internally by the framework before posting event
    • Internal Details
      Mapping of Event framework to Symbian AO
      Event Loop
    • QT Events and Symbian
      QT implements event dispatcher loop on Symbian using Active objects and Active scheduler
      However it does not use default active scheduler loop which is started with CActiveScheduler::Start()
      It manages its own event loop and use CActiveScheduler::WaitForAnyRequest() and CActiveScheduler::RunIfReady(..) methods of current active Scheduler.
      Following Active Objects are created to help implement this
      QWakeUpActiveObject: This active object helps in posted event functionality
      QTimerActiveObject: This active object helps in delivering timeout expiry events.
      QSocketActiveObject: This active object helps in delivering socket notification
      QCompleteDeferredAOs: This active object for completing deferred operations like deferred delete
      When event is posted , it is put in the thread specific queue and request completed for QWakeUpActiveObject
      Event are delivered to target QObject from QWakeUpActiveObject::RunL() using QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
      Framework takes care of completing request on appropriate thread by using RThread::RequestComplete - While posting events
      This is useful when event for a thread is posted from some other thread
    • QT Event Loop
      When we call Q[Core]Application::exec() at the end of our main() function, the application enters Qt's event loop. Conceptually, the event loop looks like this:
      while (!exit_was_called) {
      while (!posted_event_queue_is_empty) { process_next_posted_event();
      }
      while (!spontaneous_event_queue_is_empty) { process_next_spontaneous_event();
      }
      while (!posted_event_queue_is_empty) { process_next_posted_event();
      }
      }