SlideShare a Scribd company logo
Programming with Sikander
Corporate Trainer: C, Modern C++, Python, Linux System Prog
YouTube :
https://www.youtube.com/playlist?list=PLXfErIZsDibZTMKS-istzXHTTlbS0U37O
1
Multithreading
Original C++ Standard supported only
single thread programming.
The new C++ Standard, C++11, a new
thread library is introduced.
In every C++ application there is one
default main thread i.e. main() function.
We can create additional threads by
creating objects of std::thread class.
Each of the std::thread object can be
associated with a thread.
Programming with Sikander : Modern C++: Multithreading 2
Thread Creation
To start a thread we simply need to create
a new thread object and pass the
executing code to be called (i.e, a callable
object) into the constructor of the object.
Once the object is created a new thread is
launched which will execute the code
specified in callable.
The callable can be
▪ Address of function / Lambda Expression
▪ Function Object (Member Function)
Programming with Sikander : Modern C++: Multithreading 3
Waiting for threads to finish
Once a thread has started we may need to wait
for the thread to finish before we can take some
action.
To wait for a thread use the std::thread::join()
function.
This function makes the current thread wait until
the thread identified by *this has finished
executing.
Programming with Sikander : Modern C++: Multithreading 4
Thread creation – Global Function
Programming with Sikander : Modern C++: Multithreading 5
If a thread object is not initialized, it can
be assigned at a later stage.
Programming with Sikander : Modern C++: Multithreading 6
Differentiating between threads
Every running thread has an id.
Thread id can be obtained using get_id
method.
To refer to current thread: this_thread.
Every process starts a new thread
generally referred as the main thread.
Programming with Sikander : Modern C++: Multithreading 7
Programming with Sikander : Modern C++: Multithreading 8
Programming with Sikander : Modern C++: Multithreading 9
Difference between function call
and Thread
Programming with Sikander : Modern C++: Multithreading 10
Multiple threads running parallel
Programming with Sikander : Modern C++: Multithreading 11
Argument Passing to thread
Programming with Sikander : Modern C++: Multithreading 12
Passing Multiple arguments
Programming with Sikander : Modern C++: Multithreading 13
Two threads running on same
function
Programming with Sikander : Modern C++: Multithreading 14
What is the output?
Programming with Sikander : Modern C++: Multithreading 15
What is the output?
Programming with Sikander : Modern C++: Multithreading 16
Passing argument by reference
Programming with Sikander : Modern C++: Multithreading 17
Starting a Thread with a Member
Function
◼ Starting a thread with a member function
of a class requires special attention.
Programming with Sikander : Modern C++: Multithreading 18
◼ Thread Initialization
Programming with Sikander : Modern C++: Multithreading 19
Data Sharing and Race Conditions
In multithreading environment data sharing
between threads is very easy.
But this easy sharing of data can cause
problems in application.
One such problem is Race Condition.
Programming with Sikander : Modern C++: Multithreading 20
What is the output?
Programming with Sikander : Modern C++: Multithreading 21
What is the output?
Programming with Sikander : Modern C++: Multithreading 22
Race Condition
When two or more threads perform a set of
operations in parallel, that access the same
memory location.
Also, one or more thread out of them modifies
the data in that memory location, then this can
lead to an unexpected results some times.
This is called race condition.
Race conditions are usually hard to find because
they don’t occur every time.
They will occur only when relative order of
execution of operations by two or more threads
leads to an unexpected result.
Programming with Sikander : Modern C++: Multithreading 23
Race Condition
Programming with Sikander : Modern C++: Multithreading 24
Fixing Race Condition
• To fix race conditions in multi-threaded
environment we need mutex.
• Each thread needs to lock a mutex before
modifying or reading the shared data and after
modifying the data each thread should unlock the
mutex.
• The mutexes are in the <mutex> header file.
• The class representing a mutex is the std::mutex
class.
• There are two important methods of mutex:
1.) lock()
2.) unlock() Programming with Sikander : Modern C++: Multithreading 25
Mutex
A mutex is a lockable object that is
designed to signal when critical sections
of code need exclusive access, preventing
other threads with the same protection
from executing concurrently and access
the same memory locations.
Programming with Sikander : Modern C++: Multithreading 26
Programming with Sikander : Modern C++: Multithreading 27
What will happen when you forget to
unlock a mutex.
Programming with Sikander : Modern C++: Multithreading 28
Programming with Sikander : Modern C++: Multithreading 29
Mutex Management
◼
◼
Programming with Sikander : Modern C++: Multithreading 30
std::lock_guard
• A C++ Standard Library class for automatic locking
and unlocking of mutexes.
• Simple ownership model: Lock acquired on
construction, released on destruction
Example:
#include <mutex>
std::mutex myMutex;
std::lock_guard<std::mutex> lock(myMutex);
// ... critical section ...
// lock automatically released upon scope exit
Programming with Sikander : Modern C++: Multithreading 31
std::lock_guard
lock_guard wraps the mutex inside it’s object
and locks the attached mutex in its constructor.
When it’s destructor is called it releases the
mutex.
In this way, it guarantees the mutex object is
properly unlocked in case an exception is
thrown.
Programming with Sikander : Modern C++: Multithreading 32
std::lock_guard
Programming with Sikander : Modern C++: Multithreading 33
• Advantages:
• Straightforward usage.
• Minimal code for basic locking scenarios.
• Limitations:
• Lack of advanced features like deferred
locking.
Programming with Sikander : Modern C++: Multithreading 34
std::lock_guard
Std::unique_lock
A unique lock is an object that manages
a mutex object with unique ownership.
On construction, the object acquires
a mutex object, for whose locking and
unlocking operations becomes responsible.
The object supports both states: locked and
unlocked.
This class guarantees an unlocked status on
destruction (even if not called explicitly).
Programming with Sikander : Modern C++: Multithreading 35
Unique Lock
Programming with Sikander : Modern C++: Multithreading 36
Future
Futures are a high level mechanism for
passing a value between threads, and
allow a thread to wait for a result to be
available without having to manage the
locks directly.
One use of a future is to hold the result of
a call to the new async function for
running some code asynchronously
Programming with Sikander : Modern C++: Multithreading 37
Programming with Sikander : Modern C++: Multithreading 38
future<int> f=async(launch::async, calculate, 5);
future<int> f=async(launch::deferred, calculate, 5);
Programming with Sikander : Modern C++: Multithreading 39
std::promise
◼ std::promise is a C++ Standard Library class
that provides a simple mechanism for
asynchronous communication between
threads.
◼ A std::promise object represents a promise
for a value that will be made available in the
future.
◼ It is typically used in conjunction with a
std::future object, which is used to retrieve
the value at a later point in the program's
execution.
Programming with Sikander : Modern C++: Multithreading 40
Programming with Sikander : Modern C++: Multithreading 41
THANK YOU
Programming with Sikander : Modern C++: Multithreading 42

More Related Content

PDF
TypeScript
PPTX
Typescript ppt
PPT
02 c++ Array Pointer
PPTX
Python Functions
PDF
Python Spyder IDE | Edureka
PDF
What is Python Lambda Function? Python Tutorial | Edureka
PPT
Oops ppt
TypeScript
Typescript ppt
02 c++ Array Pointer
Python Functions
Python Spyder IDE | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
Oops ppt

What's hot (20)

PPTX
Delegates and events in C#
PDF
Introduction to kotlin
PDF
Class and Objects in Java
PPTX
This pointer
PPTX
Bucket your partitions wisely - Cassandra summit 2016
PPTX
Constructor in java
PPT
Functions in C++
PPT
TypeScript Presentation
PPTX
Python
PDF
Data file handling
PPTX
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
PPTX
Object oriented programming in java
PPTX
Oop c++class(final).ppt
PPTX
PPT
C++ Memory Management
PPTX
classes and objects in C++
PPTX
Function template
PDF
OOP and FP
PPTX
Constructor ppt
PDF
Operator Overloading in C++
Delegates and events in C#
Introduction to kotlin
Class and Objects in Java
This pointer
Bucket your partitions wisely - Cassandra summit 2016
Constructor in java
Functions in C++
TypeScript Presentation
Python
Data file handling
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
Object oriented programming in java
Oop c++class(final).ppt
C++ Memory Management
classes and objects in C++
Function template
OOP and FP
Constructor ppt
Operator Overloading in C++
Ad

Similar to Multithreading_in_C++ - std::thread, race condition (20)

PDF
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
PDF
Multithreaded Programming Part- I.pdf
PDF
Giorgio zoppi cpp11concurrency
PDF
Qt multi threads
PDF
Pthread
PDF
Multithreaded Programming Part- II.pdf
PDF
PPTX
Operating systems - Introduction to Threads
PPT
slides8 SharedMemory.ppt
PPT
parallel programming models
PDF
OpenHPI - Parallel Programming Concepts - Week 3
PDF
Threads lecture slides for operating systems
ODP
C11/C++11 Memory model. What is it, and why?
PPT
Shared Memory Programming with Pthreads (1).ppt
ODP
Multithreading 101
PPTX
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
PPT
Chap7 slides
PDF
chap7_slidesforparallelcomputingananthgrama
PPT
Operating Systems - "Chapter 4: Multithreaded Programming"
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
Multithreaded Programming Part- I.pdf
Giorgio zoppi cpp11concurrency
Qt multi threads
Pthread
Multithreaded Programming Part- II.pdf
Operating systems - Introduction to Threads
slides8 SharedMemory.ppt
parallel programming models
OpenHPI - Parallel Programming Concepts - Week 3
Threads lecture slides for operating systems
C11/C++11 Memory model. What is it, and why?
Shared Memory Programming with Pthreads (1).ppt
Multithreading 101
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
Chap7 slides
chap7_slidesforparallelcomputingananthgrama
Operating Systems - "Chapter 4: Multithreaded Programming"
Ad

More from Mohammed Sikander (20)

PDF
STL Containers in C++ : Sequence Container : Vector
PPTX
Strings in C - covers string functions
PDF
Smart Pointers, Modern Memory Management Techniques
PDF
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
PDF
Python_Regular Expression
PPTX
Modern_CPP-Range-Based For Loop.pptx
PDF
Modern_cpp_auto.pdf
PPTX
Python dictionary
PDF
Python exception handling
PDF
Python tuple
PDF
Python strings
PDF
Python set
PDF
Python list
PDF
Python Flow Control
PDF
Introduction to Python
PPTX
Pointer basics
PPTX
PPTX
File management
PPT
CPP Language Basics - Reference
STL Containers in C++ : Sequence Container : Vector
Strings in C - covers string functions
Smart Pointers, Modern Memory Management Techniques
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Python_Regular Expression
Modern_CPP-Range-Based For Loop.pptx
Modern_cpp_auto.pdf
Python dictionary
Python exception handling
Python tuple
Python strings
Python set
Python list
Python Flow Control
Introduction to Python
Pointer basics
File management
CPP Language Basics - Reference

Recently uploaded (20)

PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Pre independence Education in Inndia.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
master seminar digital applications in india
PPTX
Cell Structure & Organelles in detailed.
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Basic Mud Logging Guide for educational purpose
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
GDM (1) (1).pptx small presentation for students
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Insiders guide to clinical Medicine.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Computing-Curriculum for Schools in Ghana
PPH.pptx obstetrics and gynecology in nursing
Pre independence Education in Inndia.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
master seminar digital applications in india
Cell Structure & Organelles in detailed.
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Basic Mud Logging Guide for educational purpose
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
human mycosis Human fungal infections are called human mycosis..pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
GDM (1) (1).pptx small presentation for students
O5-L3 Freight Transport Ops (International) V1.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Insiders guide to clinical Medicine.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Anesthesia in Laparoscopic Surgery in India
Computing-Curriculum for Schools in Ghana

Multithreading_in_C++ - std::thread, race condition

  • 1. Programming with Sikander Corporate Trainer: C, Modern C++, Python, Linux System Prog YouTube : https://www.youtube.com/playlist?list=PLXfErIZsDibZTMKS-istzXHTTlbS0U37O 1
  • 2. Multithreading Original C++ Standard supported only single thread programming. The new C++ Standard, C++11, a new thread library is introduced. In every C++ application there is one default main thread i.e. main() function. We can create additional threads by creating objects of std::thread class. Each of the std::thread object can be associated with a thread. Programming with Sikander : Modern C++: Multithreading 2
  • 3. Thread Creation To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable. The callable can be ▪ Address of function / Lambda Expression ▪ Function Object (Member Function) Programming with Sikander : Modern C++: Multithreading 3
  • 4. Waiting for threads to finish Once a thread has started we may need to wait for the thread to finish before we can take some action. To wait for a thread use the std::thread::join() function. This function makes the current thread wait until the thread identified by *this has finished executing. Programming with Sikander : Modern C++: Multithreading 4
  • 5. Thread creation – Global Function Programming with Sikander : Modern C++: Multithreading 5
  • 6. If a thread object is not initialized, it can be assigned at a later stage. Programming with Sikander : Modern C++: Multithreading 6
  • 7. Differentiating between threads Every running thread has an id. Thread id can be obtained using get_id method. To refer to current thread: this_thread. Every process starts a new thread generally referred as the main thread. Programming with Sikander : Modern C++: Multithreading 7
  • 8. Programming with Sikander : Modern C++: Multithreading 8
  • 9. Programming with Sikander : Modern C++: Multithreading 9
  • 10. Difference between function call and Thread Programming with Sikander : Modern C++: Multithreading 10
  • 11. Multiple threads running parallel Programming with Sikander : Modern C++: Multithreading 11
  • 12. Argument Passing to thread Programming with Sikander : Modern C++: Multithreading 12
  • 13. Passing Multiple arguments Programming with Sikander : Modern C++: Multithreading 13
  • 14. Two threads running on same function Programming with Sikander : Modern C++: Multithreading 14
  • 15. What is the output? Programming with Sikander : Modern C++: Multithreading 15
  • 16. What is the output? Programming with Sikander : Modern C++: Multithreading 16
  • 17. Passing argument by reference Programming with Sikander : Modern C++: Multithreading 17
  • 18. Starting a Thread with a Member Function ◼ Starting a thread with a member function of a class requires special attention. Programming with Sikander : Modern C++: Multithreading 18 ◼ Thread Initialization
  • 19. Programming with Sikander : Modern C++: Multithreading 19
  • 20. Data Sharing and Race Conditions In multithreading environment data sharing between threads is very easy. But this easy sharing of data can cause problems in application. One such problem is Race Condition. Programming with Sikander : Modern C++: Multithreading 20
  • 21. What is the output? Programming with Sikander : Modern C++: Multithreading 21
  • 22. What is the output? Programming with Sikander : Modern C++: Multithreading 22
  • 23. Race Condition When two or more threads perform a set of operations in parallel, that access the same memory location. Also, one or more thread out of them modifies the data in that memory location, then this can lead to an unexpected results some times. This is called race condition. Race conditions are usually hard to find because they don’t occur every time. They will occur only when relative order of execution of operations by two or more threads leads to an unexpected result. Programming with Sikander : Modern C++: Multithreading 23
  • 24. Race Condition Programming with Sikander : Modern C++: Multithreading 24
  • 25. Fixing Race Condition • To fix race conditions in multi-threaded environment we need mutex. • Each thread needs to lock a mutex before modifying or reading the shared data and after modifying the data each thread should unlock the mutex. • The mutexes are in the <mutex> header file. • The class representing a mutex is the std::mutex class. • There are two important methods of mutex: 1.) lock() 2.) unlock() Programming with Sikander : Modern C++: Multithreading 25
  • 26. Mutex A mutex is a lockable object that is designed to signal when critical sections of code need exclusive access, preventing other threads with the same protection from executing concurrently and access the same memory locations. Programming with Sikander : Modern C++: Multithreading 26
  • 27. Programming with Sikander : Modern C++: Multithreading 27
  • 28. What will happen when you forget to unlock a mutex. Programming with Sikander : Modern C++: Multithreading 28
  • 29. Programming with Sikander : Modern C++: Multithreading 29
  • 30. Mutex Management ◼ ◼ Programming with Sikander : Modern C++: Multithreading 30
  • 31. std::lock_guard • A C++ Standard Library class for automatic locking and unlocking of mutexes. • Simple ownership model: Lock acquired on construction, released on destruction Example: #include <mutex> std::mutex myMutex; std::lock_guard<std::mutex> lock(myMutex); // ... critical section ... // lock automatically released upon scope exit Programming with Sikander : Modern C++: Multithreading 31
  • 32. std::lock_guard lock_guard wraps the mutex inside it’s object and locks the attached mutex in its constructor. When it’s destructor is called it releases the mutex. In this way, it guarantees the mutex object is properly unlocked in case an exception is thrown. Programming with Sikander : Modern C++: Multithreading 32
  • 33. std::lock_guard Programming with Sikander : Modern C++: Multithreading 33
  • 34. • Advantages: • Straightforward usage. • Minimal code for basic locking scenarios. • Limitations: • Lack of advanced features like deferred locking. Programming with Sikander : Modern C++: Multithreading 34 std::lock_guard
  • 35. Std::unique_lock A unique lock is an object that manages a mutex object with unique ownership. On construction, the object acquires a mutex object, for whose locking and unlocking operations becomes responsible. The object supports both states: locked and unlocked. This class guarantees an unlocked status on destruction (even if not called explicitly). Programming with Sikander : Modern C++: Multithreading 35
  • 36. Unique Lock Programming with Sikander : Modern C++: Multithreading 36
  • 37. Future Futures are a high level mechanism for passing a value between threads, and allow a thread to wait for a result to be available without having to manage the locks directly. One use of a future is to hold the result of a call to the new async function for running some code asynchronously Programming with Sikander : Modern C++: Multithreading 37
  • 38. Programming with Sikander : Modern C++: Multithreading 38
  • 39. future<int> f=async(launch::async, calculate, 5); future<int> f=async(launch::deferred, calculate, 5); Programming with Sikander : Modern C++: Multithreading 39
  • 40. std::promise ◼ std::promise is a C++ Standard Library class that provides a simple mechanism for asynchronous communication between threads. ◼ A std::promise object represents a promise for a value that will be made available in the future. ◼ It is typically used in conjunction with a std::future object, which is used to retrieve the value at a later point in the program's execution. Programming with Sikander : Modern C++: Multithreading 40
  • 41. Programming with Sikander : Modern C++: Multithreading 41
  • 42. THANK YOU Programming with Sikander : Modern C++: Multithreading 42