SlideShare a Scribd company logo
1 of 17
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();  	}  }

More Related Content

What's hot

Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIICS
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4ICS
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIICS
 
Qt for beginners part 1 overview and key concepts
Qt for beginners part 1   overview and key conceptsQt for beginners part 1   overview and key concepts
Qt for beginners part 1 overview and key conceptsICS
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentICS
 
Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4ICS
 
Qt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickQt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickICS
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical PresentationDaniel Rocha
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IICS
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesLessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesICS
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QMLAlan Uthoff
 
Qt for Python
Qt for PythonQt for Python
Qt for PythonICS
 

What's hot (20)

Introduction to Qt programming
Introduction to Qt programmingIntroduction to Qt programming
Introduction to Qt programming
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 
UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4
 
IPC with Qt
IPC with QtIPC with Qt
IPC with Qt
 
Qt 5 - C++ and Widgets
Qt 5 - C++ and WidgetsQt 5 - C++ and Widgets
Qt 5 - C++ and Widgets
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
Qt for beginners part 1 overview and key concepts
Qt for beginners part 1   overview and key conceptsQt for beginners part 1   overview and key concepts
Qt for beginners part 1 overview and key concepts
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Hello, QML
Hello, QMLHello, QML
Hello, QML
 
Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI development
 
Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4
 
Qt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickQt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt Quick
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical Presentation
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part I
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesLessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
 
Qt for Python
Qt for PythonQt for Python
Qt for Python
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 

Viewers also liked

2015 functional genomics variant annotation and interpretation- tools and p...
2015 functional genomics   variant annotation and interpretation- tools and p...2015 functional genomics   variant annotation and interpretation- tools and p...
2015 functional genomics variant annotation and interpretation- tools and p...Gabe Rudy
 
UCSD / DBMI seminar 2015-02-6
UCSD / DBMI seminar 2015-02-6UCSD / DBMI seminar 2015-02-6
UCSD / DBMI seminar 2015-02-6Andrew Su
 
Open biomedical knowledge using crowdsourcing and citizen science
Open biomedical knowledge using crowdsourcing and citizen scienceOpen biomedical knowledge using crowdsourcing and citizen science
Open biomedical knowledge using crowdsourcing and citizen scienceAndrew Su
 
MyGene.info talk at ISMB/BOSC 2013
MyGene.info talk at ISMB/BOSC 2013MyGene.info talk at ISMB/BOSC 2013
MyGene.info talk at ISMB/BOSC 2013anewgene
 
MyGene.info learn-more
MyGene.info learn-moreMyGene.info learn-more
MyGene.info learn-moreanewgene
 
New Generation Sequencing Technologies: an overview
New Generation Sequencing Technologies: an overviewNew Generation Sequencing Technologies: an overview
New Generation Sequencing Technologies: an overviewPaolo Dametto
 
Next generation sequencing
Next generation sequencingNext generation sequencing
Next generation sequencingDayananda Salam
 
Next Gen Sequencing (NGS) Technology Overview
Next Gen Sequencing (NGS) Technology OverviewNext Gen Sequencing (NGS) Technology Overview
Next Gen Sequencing (NGS) Technology OverviewDominic Suciu
 
NGS technologies - platforms and applications
NGS technologies - platforms and applicationsNGS technologies - platforms and applications
NGS technologies - platforms and applicationsAGRF_Ltd
 
A Comparison of NGS Platforms.
A Comparison of NGS Platforms.A Comparison of NGS Platforms.
A Comparison of NGS Platforms.mkim8
 
NGS - Basic principles and sequencing platforms
NGS - Basic principles and sequencing platformsNGS - Basic principles and sequencing platforms
NGS - Basic principles and sequencing platformsAnnelies Haegeman
 

Viewers also liked (15)

2015 functional genomics variant annotation and interpretation- tools and p...
2015 functional genomics   variant annotation and interpretation- tools and p...2015 functional genomics   variant annotation and interpretation- tools and p...
2015 functional genomics variant annotation and interpretation- tools and p...
 
UCSD / DBMI seminar 2015-02-6
UCSD / DBMI seminar 2015-02-6UCSD / DBMI seminar 2015-02-6
UCSD / DBMI seminar 2015-02-6
 
F01-Cloud-Mygene.info
F01-Cloud-Mygene.infoF01-Cloud-Mygene.info
F01-Cloud-Mygene.info
 
Open biomedical knowledge using crowdsourcing and citizen science
Open biomedical knowledge using crowdsourcing and citizen scienceOpen biomedical knowledge using crowdsourcing and citizen science
Open biomedical knowledge using crowdsourcing and citizen science
 
MyGene.info talk at ISMB/BOSC 2013
MyGene.info talk at ISMB/BOSC 2013MyGene.info talk at ISMB/BOSC 2013
MyGene.info talk at ISMB/BOSC 2013
 
MyGene.info learn-more
MyGene.info learn-moreMyGene.info learn-more
MyGene.info learn-more
 
Ensembl Browser Workshop
Ensembl Browser WorkshopEnsembl Browser Workshop
Ensembl Browser Workshop
 
New Generation Sequencing Technologies: an overview
New Generation Sequencing Technologies: an overviewNew Generation Sequencing Technologies: an overview
New Generation Sequencing Technologies: an overview
 
Next generation sequencing
Next generation sequencingNext generation sequencing
Next generation sequencing
 
Next Gen Sequencing (NGS) Technology Overview
Next Gen Sequencing (NGS) Technology OverviewNext Gen Sequencing (NGS) Technology Overview
Next Gen Sequencing (NGS) Technology Overview
 
NGS technologies - platforms and applications
NGS technologies - platforms and applicationsNGS technologies - platforms and applications
NGS technologies - platforms and applications
 
Ngs ppt
Ngs pptNgs ppt
Ngs ppt
 
A Comparison of NGS Platforms.
A Comparison of NGS Platforms.A Comparison of NGS Platforms.
A Comparison of NGS Platforms.
 
Introduction to next generation sequencing
Introduction to next generation sequencingIntroduction to next generation sequencing
Introduction to next generation sequencing
 
NGS - Basic principles and sequencing platforms
NGS - Basic principles and sequencing platformsNGS - Basic principles and sequencing platforms
NGS - Basic principles and sequencing platforms
 

Similar to Threads, Events, Signals/Slots in QT

Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Event and signal driven programming
Event and signal driven programmingEvent and signal driven programming
Event and signal driven programmingElizabeth Smith
 
Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Elizabeth Smith
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Androidgreenrobot
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Building Cross-Platform Apps using Qt and Qyoto
Building Cross-Platform Apps using Qt and QyotoBuilding Cross-Platform Apps using Qt and Qyoto
Building Cross-Platform Apps using Qt and QyotoJeff Alstadt
 
OSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersOSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersAruna Karunarathna
 
Microservices with Netflix OSS & Spring Cloud - Arnaud Cogoluègnes
 Microservices with Netflix OSS & Spring Cloud - Arnaud Cogoluègnes Microservices with Netflix OSS & Spring Cloud - Arnaud Cogoluègnes
Microservices with Netflix OSS & Spring Cloud - Arnaud Cogoluègnesdistributed matters
 
Microservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring CloudMicroservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring Cloudacogoluegnes
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 appletsraksharao
 

Similar to Threads, Events, Signals/Slots in QT (20)

Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Reactors.io
Reactors.ioReactors.io
Reactors.io
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 
Event and signal driven programming
Event and signal driven programmingEvent and signal driven programming
Event and signal driven programming
 
Pharos
PharosPharos
Pharos
 
Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012
 
Tech talk
Tech talkTech talk
Tech talk
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Android
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Treinamento Qt básico - aula II
Treinamento Qt básico - aula IITreinamento Qt básico - aula II
Treinamento Qt básico - aula II
 
Aglets
AgletsAglets
Aglets
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Building Cross-Platform Apps using Qt and Qyoto
Building Cross-Platform Apps using Qt and QyotoBuilding Cross-Platform Apps using Qt and Qyoto
Building Cross-Platform Apps using Qt and Qyoto
 
OSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersOSGi Training for Carbon Developers
OSGi Training for Carbon Developers
 
Microservices with Netflix OSS & Spring Cloud - Arnaud Cogoluègnes
 Microservices with Netflix OSS & Spring Cloud - Arnaud Cogoluègnes Microservices with Netflix OSS & Spring Cloud - Arnaud Cogoluègnes
Microservices with Netflix OSS & Spring Cloud - Arnaud Cogoluègnes
 
Microservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring CloudMicroservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring Cloud
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
IoT in salsa Serverless
IoT in salsa ServerlessIoT in salsa Serverless
IoT in salsa Serverless
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 

Threads, Events, Signals/Slots in QT

  • 1. Threads, Events, Signals/Slots Multithreaded Programming in QT
  • 2. 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
  • 3. 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()
  • 4. 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
  • 5. 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.
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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.
  • 10. 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)) );
  • 11. 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++
  • 12. 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.
  • 13. 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.
  • 14. 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
  • 15. Internal Details Mapping of Event framework to Symbian AO Event Loop
  • 16. 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
  • 17. 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(); } }