SlideShare a Scribd company logo
1 of 21
Download to read offline
Integrated Computer Solutions Inc. www.ics.com
Lock Less With Producer
Consumer Threads
Efficiently Marshalling Data from Producer Threads
1
Integrated Computer Solutions Inc. www.ics.com
Common Scenarios
Data communications may be a blocking operation
Need to spawn a thread to handle it.
Data communications happens in another thread
This thread may not even be created within your application.
3rd party library spawns this thread
Callbacks or Listeners are called from this thread and NOT the main GUI thread.
Data structures need to be protected.
One thread isn’t reading while another thread is writing.
2
Integrated Computer Solutions Inc. www.ics.com
QML Performance Considerations
QML bindings require properties to return as quick as possible
Properties may be used in N different bindings
Bindings may cause properties to be fetched quite often
value : cppModel.a + cppModel.b + cppModel.c
3
Integrated Computer Solutions Inc. www.ics.com
Lockless Thread Communications
Not to be confused with “Lock Free” thread communications
Where there are no locks.
We are going to use fewer locks and lock them less often.
Lockless is much like stainless steel.
It can rust, but a whole lot less than steel.
Less can be more when it comes to locking threads.
4
Integrated Computer Solutions Inc. www.ics.com
Less Efficient Solution (Model Locks)
Locks inside data models
Every setter locks a mutex (or other lock)
Every getter locks a mutex (or other lock)
This is fairly low risk. All locks are hidden from client code.
Client code usually can’t cause deadlock
However, there is a whole lot of locking going on
A value maybe updated often (writing)
That value could be used in a lot of QML bindings (reading)
5
Integrated Computer Solutions Inc. www.ics.com
Error Prone Solution (External locking)
Client code locks and unlocks model.
May be better because you can lock once, update as much as you like, unlock.
Less thread context switching.
Error prone because client code can now cause a deadlock bug
Because of the way QML works you can’t bundle reads.
Would still lock on every property read.
Or you’d have to write some hairy code to copy the data.
6
Integrated Computer Solutions Inc. www.ics.com
Producer Consumer Solution
Updated values are added to a shared queue
Communications thread adds to the queue or ring buffer
GUI thread takes items off the queue or ring buffer
GUI thread would need a way to monitor the queue for new values
Event loop integration, etc
There is a fair bit of non-trivial code to write for this solution
If you used some other toolkit…..
Much less locking involved.
7
Integrated Computer Solutions Inc. www.ics.com
Qt’s Automagical Producer Consumer System
Qt has a shared queue to communicate with the GUI thread
The Qt event loop!
Qt has a simple way to integrate with the event loop
Cross thread signals and slots.
We can simply use this mechanism to get producer consumer with very little code
8
Integrated Computer Solutions Inc. www.ics.com
Cross Thread Signals and Slots
9
Worker Thread Main Thread
void handlePacket(const Packet& p)
{
// Decode packet
// Convert data types, etc
emit temperatureChanged(temp);
}
void Model::setTemperature(double temp)
{
m_temperature = temp;
emit temperatureChanged();
}
double temperature() const
{
return m_temperature;
}
Qt locks here
Integrated Computer Solutions Inc. www.ics.com
How Cross Thread Signals and Slots Work
Qt signals and slots have 4 connection types
Direct - Signal causes connected slots to be called via blocking function calls
This is how most slots are called. You can step from signal to slot.
Queued - Signal causes events to be added to an event queue
These events copy the parameters.
The event calls the slot when handled.
BlockingQueuedConnection - Queued, but blocks the calling thread.
Avoid using this. If you use it wrong you will deadlock.
10
Integrated Computer Solutions Inc. www.ics.com
AutoConnection
AutoConnection - Direct vs Queued is decided when a signal is emitted.
The thread id of the current thread (where emit happens) is checked
against the receiver object’s “preferred thread”.
The Qt docs call this the QObject’s thread affinity.
Thread ids match - Direct Connection
Thread ids do match - Queued Connection
11
Integrated Computer Solutions Inc. www.ics.com
How To Set QObject Thread Affinity
QObjects default to the thread they were created in.
QObject::moveToThread(QThread* thread)
This will cause slots to be called in thread’s context when using auto
connection
Receivers always need to prefer the main thread or a QThread.
Because being on the receiving end of a cross thread signal requires an
event loop
For our purposes we don’t need to move any objects.
All the receivers prefer the main gui thread.
12
Integrated Computer Solutions Inc. www.ics.com
Emitting From Other Threads
No special code required.
You can emit from any thread.
Does not need to be a QThread
Could be pthread, std::thread, etc
13
Integrated Computer Solutions Inc. www.ics.com
Registering QVariant Types
Parameters passed via cross thread signals and slots need to be QVariant
compatible
Default constructor
Copy constructor
Assignment operator
Use Q_DECALRE_METATYPE(TypeName) in header
Use qRegisterMetaType<TypeName>(“TypeName”) in code
Enums also have to registered
14
Integrated Computer Solutions Inc. www.ics.com
What about costly copies? Implicit sharing!
Most Qt data structures are implicitly shared.
QString, QByteArray, QImage
QVector, QList, QMap, QHash, etc
Copy on write semantics
Assignment operator only increments a reference count
Makes passing large data between threads much faster.
As long as you don’t change the data. That will cause a detach().
15
Integrated Computer Solutions Inc. www.ics.com
Implicit Sharing
// 10 MB Char Array
QByteArray hugeData(1024 * 1024 * 10, ‘X’);
// Reference count increment.
// No memory allocated here for anotherArray.
// Points to hugeArray’s data.
QByteArray anotherData = hugeData;
// Modify the anotherData array.
// This will call detach() which decrements the ref count and copies hugeData
// before modifying one char in the array.
anotherData[4242] = ‘Y’;
16
Integrated Computer Solutions Inc. www.ics.com
Implicit Sharing Tips
Implicit sharing is a blessing and a curse
Good - “Copies” of unmodified data are very fast.
Good - Reference count is thread safe using atomics
Bad - Debugging performance issues can become a hassle
It’s not obvious where data is copied.
Look for stacks with ::detach() in profiling data
17
Integrated Computer Solutions Inc. www.ics.com
Example Adapting Callbacks To Signals/Slots
18
Integrated Computer Solutions Inc. www.ics.com
QThread Example
19
Integrated Computer Solutions Inc. www.ics.com
Pros and Cons
Pros:
Faster reads for QML properties.
Much simpler code. Easier to maintain.
Only need to understand basic Qt Signals and Slots to extend.
Threading details are completely hidden.
Cons:
Very high frequency data can log jamb the event queue.
20
Integrated Computer Solutions Inc. www.ics.com
Thank You!
21

More Related Content

What's hot

What's hot (20)

Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2
 
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 multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
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
 
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
 
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
 
Intro to QML / Declarative UI
Intro to QML / Declarative UIIntro to QML / Declarative UI
Intro to QML / Declarative UI
 
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
 
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
 
Meet the Widgets: Another Way to Implement UI
Meet the Widgets: Another Way to Implement UIMeet the Widgets: Another Way to Implement UI
Meet the Widgets: Another Way to Implement UI
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application Framework
 
So I Downloaded Qt, Now What?
So I Downloaded Qt, Now What?So I Downloaded Qt, Now What?
So I Downloaded Qt, Now What?
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IV
 
Introduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphIntroduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene Graph
 
QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong?
 
Qt and QML performance tips & tricks for Qt 4.7
Qt and QML performance tips & tricks for Qt 4.7Qt and QML performance tips & tricks for Qt 4.7
Qt and QML performance tips & tricks for Qt 4.7
 
Serving QML applications over the network
Serving QML applications over the networkServing QML applications over the network
Serving QML applications over the network
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Qt for beginners part 5 ask the experts
Qt for beginners part 5   ask the expertsQt for beginners part 5   ask the experts
Qt for beginners part 5 ask the experts
 

Similar to Lockless Producer Consumer Threads: Asynchronous Communications Made Easy

The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
aviade
 
The hardest part of microservices: your data
The hardest part of microservices: your dataThe hardest part of microservices: your data
The hardest part of microservices: your data
Christian Posta
 
Network And Network Address Translation
Network And Network Address TranslationNetwork And Network Address Translation
Network And Network Address Translation
Erin Moore
 

Similar to Lockless Producer Consumer Threads: Asynchronous Communications Made Easy (20)

DDD Framework for Java: JdonFramework
DDD Framework for Java: JdonFrameworkDDD Framework for Java: JdonFramework
DDD Framework for Java: JdonFramework
 
Low latency in java 8 v5
Low latency in java 8 v5Low latency in java 8 v5
Low latency in java 8 v5
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
 
Developing Real-Time Data Pipelines with Apache Kafka
Developing Real-Time Data Pipelines with Apache KafkaDeveloping Real-Time Data Pipelines with Apache Kafka
Developing Real-Time Data Pipelines with Apache Kafka
 
Future prediction-ds
Future prediction-dsFuture prediction-ds
Future prediction-ds
 
Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey Low latency in java 8 by Peter Lawrey
Low latency in java 8 by Peter Lawrey
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
 
Shopzilla On Concurrency
Shopzilla On ConcurrencyShopzilla On Concurrency
Shopzilla On Concurrency
 
GCF
GCFGCF
GCF
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Wood
 
The hardest part of microservices: your data
The hardest part of microservices: your dataThe hardest part of microservices: your data
The hardest part of microservices: your data
 
Linking Programming models between Grids, Web 2.0 and Multicore
Linking Programming models between Grids, Web 2.0 and Multicore Linking Programming models between Grids, Web 2.0 and Multicore
Linking Programming models between Grids, Web 2.0 and Multicore
 
.net Framework
.net Framework.net Framework
.net Framework
 
Dot net interview questions and asnwers
Dot net interview questions and asnwersDot net interview questions and asnwers
Dot net interview questions and asnwers
 
Concurrency and parallel in .net
Concurrency and parallel in .netConcurrency and parallel in .net
Concurrency and parallel in .net
 
Security Tips to run Docker in Production
Security Tips to run Docker in ProductionSecurity Tips to run Docker in Production
Security Tips to run Docker in Production
 
Implementare e gestire soluzioni per l'Internet of Things (IoT) in modo rapid...
Implementare e gestire soluzioni per l'Internet of Things (IoT) in modo rapid...Implementare e gestire soluzioni per l'Internet of Things (IoT) in modo rapid...
Implementare e gestire soluzioni per l'Internet of Things (IoT) in modo rapid...
 
Enterprise Library 2.0
Enterprise Library 2.0Enterprise Library 2.0
Enterprise Library 2.0
 
Network And Network Address Translation
Network And Network Address TranslationNetwork And Network Address Translation
Network And Network Address Translation
 

More from ICS

Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
ICS
 

More from ICS (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Practical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdfPractical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdf
 
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
 
Overcoming CMake Configuration Issues Webinar
Overcoming CMake Configuration Issues WebinarOvercoming CMake Configuration Issues Webinar
Overcoming CMake Configuration Issues Webinar
 
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
Enhancing Quality and Test in Medical Device Design - Part 2.pdfEnhancing Quality and Test in Medical Device Design - Part 2.pdf
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
 
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdfDesigning and Managing IoT Devices for Rapid Deployment - Webinar.pdf
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
 
Quality and Test in Medical Device Design - Part 1.pdf
Quality and Test in Medical Device Design - Part 1.pdfQuality and Test in Medical Device Design - Part 1.pdf
Quality and Test in Medical Device Design - Part 1.pdf
 
Creating Digital Twins Using Rapid Development Techniques.pdf
Creating Digital Twins Using Rapid Development Techniques.pdfCreating Digital Twins Using Rapid Development Techniques.pdf
Creating Digital Twins Using Rapid Development Techniques.pdf
 
Secure Your Medical Devices From the Ground Up
Secure Your Medical Devices From the Ground Up Secure Your Medical Devices From the Ground Up
Secure Your Medical Devices From the Ground Up
 
Cybersecurity and Software Updates in Medical Devices.pdf
Cybersecurity and Software Updates in Medical Devices.pdfCybersecurity and Software Updates in Medical Devices.pdf
Cybersecurity and Software Updates in Medical Devices.pdf
 
MDG Panel - Creating Expert Level GUIs for Complex Medical Devices
MDG Panel - Creating Expert Level GUIs for Complex Medical DevicesMDG Panel - Creating Expert Level GUIs for Complex Medical Devices
MDG Panel - Creating Expert Level GUIs for Complex Medical Devices
 
How to Craft a Winning IOT Device Management Solution
How to Craft a Winning IOT Device Management SolutionHow to Craft a Winning IOT Device Management Solution
How to Craft a Winning IOT Device Management Solution
 
Bridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory TeamsBridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory Teams
 
IoT Device Fleet Management: Create a Robust Solution with Azure
IoT Device Fleet Management: Create a Robust Solution with AzureIoT Device Fleet Management: Create a Robust Solution with Azure
IoT Device Fleet Management: Create a Robust Solution with Azure
 
Basic Cmake for Qt Users
Basic Cmake for Qt UsersBasic Cmake for Qt Users
Basic Cmake for Qt Users
 
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
 
Qt Installer Framework
Qt Installer FrameworkQt Installer Framework
Qt Installer Framework
 
Bridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory TeamsBridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory Teams
 
Overcome Hardware And Software Challenges - Medical Device Case Study
Overcome Hardware And Software Challenges - Medical Device Case StudyOvercome Hardware And Software Challenges - Medical Device Case Study
Overcome Hardware And Software Challenges - Medical Device Case Study
 
User Experience Design for IoT
User Experience Design for IoTUser Experience Design for IoT
User Experience Design for IoT
 

Recently uploaded

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

Lockless Producer Consumer Threads: Asynchronous Communications Made Easy

  • 1. Integrated Computer Solutions Inc. www.ics.com Lock Less With Producer Consumer Threads Efficiently Marshalling Data from Producer Threads 1
  • 2. Integrated Computer Solutions Inc. www.ics.com Common Scenarios Data communications may be a blocking operation Need to spawn a thread to handle it. Data communications happens in another thread This thread may not even be created within your application. 3rd party library spawns this thread Callbacks or Listeners are called from this thread and NOT the main GUI thread. Data structures need to be protected. One thread isn’t reading while another thread is writing. 2
  • 3. Integrated Computer Solutions Inc. www.ics.com QML Performance Considerations QML bindings require properties to return as quick as possible Properties may be used in N different bindings Bindings may cause properties to be fetched quite often value : cppModel.a + cppModel.b + cppModel.c 3
  • 4. Integrated Computer Solutions Inc. www.ics.com Lockless Thread Communications Not to be confused with “Lock Free” thread communications Where there are no locks. We are going to use fewer locks and lock them less often. Lockless is much like stainless steel. It can rust, but a whole lot less than steel. Less can be more when it comes to locking threads. 4
  • 5. Integrated Computer Solutions Inc. www.ics.com Less Efficient Solution (Model Locks) Locks inside data models Every setter locks a mutex (or other lock) Every getter locks a mutex (or other lock) This is fairly low risk. All locks are hidden from client code. Client code usually can’t cause deadlock However, there is a whole lot of locking going on A value maybe updated often (writing) That value could be used in a lot of QML bindings (reading) 5
  • 6. Integrated Computer Solutions Inc. www.ics.com Error Prone Solution (External locking) Client code locks and unlocks model. May be better because you can lock once, update as much as you like, unlock. Less thread context switching. Error prone because client code can now cause a deadlock bug Because of the way QML works you can’t bundle reads. Would still lock on every property read. Or you’d have to write some hairy code to copy the data. 6
  • 7. Integrated Computer Solutions Inc. www.ics.com Producer Consumer Solution Updated values are added to a shared queue Communications thread adds to the queue or ring buffer GUI thread takes items off the queue or ring buffer GUI thread would need a way to monitor the queue for new values Event loop integration, etc There is a fair bit of non-trivial code to write for this solution If you used some other toolkit….. Much less locking involved. 7
  • 8. Integrated Computer Solutions Inc. www.ics.com Qt’s Automagical Producer Consumer System Qt has a shared queue to communicate with the GUI thread The Qt event loop! Qt has a simple way to integrate with the event loop Cross thread signals and slots. We can simply use this mechanism to get producer consumer with very little code 8
  • 9. Integrated Computer Solutions Inc. www.ics.com Cross Thread Signals and Slots 9 Worker Thread Main Thread void handlePacket(const Packet& p) { // Decode packet // Convert data types, etc emit temperatureChanged(temp); } void Model::setTemperature(double temp) { m_temperature = temp; emit temperatureChanged(); } double temperature() const { return m_temperature; } Qt locks here
  • 10. Integrated Computer Solutions Inc. www.ics.com How Cross Thread Signals and Slots Work Qt signals and slots have 4 connection types Direct - Signal causes connected slots to be called via blocking function calls This is how most slots are called. You can step from signal to slot. Queued - Signal causes events to be added to an event queue These events copy the parameters. The event calls the slot when handled. BlockingQueuedConnection - Queued, but blocks the calling thread. Avoid using this. If you use it wrong you will deadlock. 10
  • 11. Integrated Computer Solutions Inc. www.ics.com AutoConnection AutoConnection - Direct vs Queued is decided when a signal is emitted. The thread id of the current thread (where emit happens) is checked against the receiver object’s “preferred thread”. The Qt docs call this the QObject’s thread affinity. Thread ids match - Direct Connection Thread ids do match - Queued Connection 11
  • 12. Integrated Computer Solutions Inc. www.ics.com How To Set QObject Thread Affinity QObjects default to the thread they were created in. QObject::moveToThread(QThread* thread) This will cause slots to be called in thread’s context when using auto connection Receivers always need to prefer the main thread or a QThread. Because being on the receiving end of a cross thread signal requires an event loop For our purposes we don’t need to move any objects. All the receivers prefer the main gui thread. 12
  • 13. Integrated Computer Solutions Inc. www.ics.com Emitting From Other Threads No special code required. You can emit from any thread. Does not need to be a QThread Could be pthread, std::thread, etc 13
  • 14. Integrated Computer Solutions Inc. www.ics.com Registering QVariant Types Parameters passed via cross thread signals and slots need to be QVariant compatible Default constructor Copy constructor Assignment operator Use Q_DECALRE_METATYPE(TypeName) in header Use qRegisterMetaType<TypeName>(“TypeName”) in code Enums also have to registered 14
  • 15. Integrated Computer Solutions Inc. www.ics.com What about costly copies? Implicit sharing! Most Qt data structures are implicitly shared. QString, QByteArray, QImage QVector, QList, QMap, QHash, etc Copy on write semantics Assignment operator only increments a reference count Makes passing large data between threads much faster. As long as you don’t change the data. That will cause a detach(). 15
  • 16. Integrated Computer Solutions Inc. www.ics.com Implicit Sharing // 10 MB Char Array QByteArray hugeData(1024 * 1024 * 10, ‘X’); // Reference count increment. // No memory allocated here for anotherArray. // Points to hugeArray’s data. QByteArray anotherData = hugeData; // Modify the anotherData array. // This will call detach() which decrements the ref count and copies hugeData // before modifying one char in the array. anotherData[4242] = ‘Y’; 16
  • 17. Integrated Computer Solutions Inc. www.ics.com Implicit Sharing Tips Implicit sharing is a blessing and a curse Good - “Copies” of unmodified data are very fast. Good - Reference count is thread safe using atomics Bad - Debugging performance issues can become a hassle It’s not obvious where data is copied. Look for stacks with ::detach() in profiling data 17
  • 18. Integrated Computer Solutions Inc. www.ics.com Example Adapting Callbacks To Signals/Slots 18
  • 19. Integrated Computer Solutions Inc. www.ics.com QThread Example 19
  • 20. Integrated Computer Solutions Inc. www.ics.com Pros and Cons Pros: Faster reads for QML properties. Much simpler code. Easier to maintain. Only need to understand basic Qt Signals and Slots to extend. Threading details are completely hidden. Cons: Very high frequency data can log jamb the event queue. 20
  • 21. Integrated Computer Solutions Inc. www.ics.com Thank You! 21