0% found this document useful (0 votes)
46 views22 pages

Multithreading in C++ by Mandeep Punia

Cpp

Uploaded by

2193maddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views22 pages

Multithreading in C++ by Mandeep Punia

Cpp

Uploaded by

2193maddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

MultiThreading in C++

Q) What do you understand by thread and give one example?

Ans: In every application there is default thread which is main(), in side


this we create other threads.

A thread is also known as lightweight process.


For example:

1. MS word must be using multiple threads, one thread to format


the text, another thread to process inputs (spell checker)
2. The browser has multiple tabs that can be different threads

Q) Why we need threading in programming which problem it is trying


to solve?

Ans: This idea is to achieve parallelism by dividing a process into


multiple threads. Have you wondered how visual studio code editor is
able to do code completion! This must be done using threading for auto
completing the code ( Intellisense).

So, in order to achieve multitasking we use threads in our systems so


that more than one tasks can be executed simultaneously.

Multitasking is of two types: Processor based and thread based.

Processor based multitasking is managed by the OS.

However, thread based multitasking can be achieved by the


programmer using multithreading.
Example of Single threaded program Which we usually write
when we start learning programming
Above sample program if written using threads will look like this

Wooooah , It saved our time from 4 seconds to 1 second ,it may defer
everytime you run program , but certainly will be less then the above
one .
Ways to create Thread in C++11:

1) Threading using function pointer


2) Threading using Lambda function
3) Threading using Functors
4) Threading using Non static member function
5) Threading using Static member function
Join and Detach in C++
Join :-

Once a thread is started we wait for this thread to finish by calling join()
function on thread object.

Double join will result into program termination ( crash will happen i.e.,
core dump)
So what happened in this program is , a
call is made to the OS to create a thread
for run function and then the control
returned back to the main thread and it
started execution for the main thread
(meanwhile run thread is running) then
it goes again to run thread executed it a
bit and then come back again and so on
and so for and executed the stuff until
t.join() is encountered. Once t.join() is
encountered it waits for run thread to
complete its execution and then it
proceed further. (but in this example run
thread completed its execution before
t.join occurred ).
If needed we should check thread is joinable before joining ( using
joinable() function) ( It’s a good practice as well ).
Detach:

This is used to detach newly created thread from the parent thread.

Always check before detaching a thread that it is joinable otherwise we


may end up double detaching and double detach() will result into
program termination.

If we have detached thread and main function is returning then the


detached thread execution is suspended.

So, in this program as soon as run thread is created and started its
execution control returned to the main thread then detached the
thread and completed its execution and the program finished . Nothing
executed for run thread. run thread has been suspened and no longer
available to the parent thread.
The moment you create a thread that thread is marked as joinable
and then later once either you apply join() or detach() on that
thread then it automatically becomes non-joinable.

So, either join() or detach() should be called on thread object ,


otherwise during thread object’s destructor it will terminate the
program because inside destructor it checks if thread is still
joinable? If yes, then it terminate the program.
Mutex in C++: Mutual Exclusion

Race Condition: is a situation where two or more threads/process


happens to change a common data at the same time.

If there is a Race condition then we have to protect it and the protected


section is called the critical section.

** When two or more than two threads are simultaneously trying to


modify data than there is a race condition. When you are
simultaneously trying to access the data then there is no race condition.

If two threads are simultaneously trying to load the data ( let’s say
integer x=0) than they are trying to load in accumulator register then
both the processes will have x=0 then they happen to increment it to
x=1 at both the places and then stored back. So x=1 will go back.

Can you see the problem here! This is called as the race condition.

(As both of these threads are racing for the common variable)
Race Condition Example program

Here x is myAmount
In order to avoid Race condition, we use lock

Race Condition is removed here,


now only one thread can access
myAmount data/resource at a
time.

Mutex Try Lock:

try_lock() tries to lock the mutex. It Returns immediately. On successful


lock acquisition it returns true otherwise returns false.

 If try_lock() is not able to lock mutex, then it doesn’t get blocked


that’s why it is called non-blocking.
 If try_lock() is called again by the same thread which owns the
mutex , the behavior is undefined . It is a dead lock situation with
undefined behavior ( if you want to be able to lock the same
mutex by same thread more than one time then go for recursive
mutex)

This program output will be different


everytime when you run it & the
reason why it is happening is because
of the try_lock() which locked mutex
and on the same time when other
thread is trying to lock it , the
try_locked() returned false and it
doesn’t went inside if block for that
corresponding thread & skipped to
the next iteration.
std::try_lock() in C++11 Threading :

1) std::try_lock() tries to lock all the lockable objects passed in it one by


one in given order.

SYNTAX: std::try_lock(m1,m2,m3,m4….,mn);

2) On Success this function returns -1 otherwise it will return 0-based


,mutex index number which it could not lock.

3) If it fails to lock any of the mutex then it will release all the mutex it
locked before

4) If a call to try_lock() results in an exception , unlock is called for any


locked objects before rethrowing.

The actual use of std::try_lock() function is , it can try to lock multiple


mutex objects at the same time.

Timed mutex in C++ Threading:

std::timed_mutex is blocked till timeout time and returns true if success


otherwise false.
try_lock_for():

Thread 2 waited for 2 seconds to get


the lock and as we can see that sleep
is for only 1 seconds so whichever
thread acquires it first will definitely
release it within 2 seconds and then
other thread can acquire it.
try_lock_until(): try_lock_until is similar to try_lock_for
Condition Variable in C++: Condition variable are used for two purpose

1) Notify other threads


2) Waiting for some conditions

Condition variable allows running threads to wait on some conditions


and once those conditions are met the waiting thread is notified using:

1) notify_one()
2) notify_all()

You need mutex to use condition variable.

If some thread want to wait on some condition then it has to do these


things:

 Acquire the mutex lock using


std::unique_lock<std::mutex>lock(m);
 Execute wait, wait_for or wait_until. The wait operation
automatically release the mutex and suspend the execution of the
thread.
 When the condition variable is notified , the thread is awakened
and the mutex is automatically reacquired. The thread then
should check the condition and resume waiting if the wake_up
was spurious.

Condition variable are used to synchronize two or more threads.

Best use case of condition variable is Consumer/Producer problem.


In line no. 18, mutex is locked then in
line no.19 , we have used condition
variable cv in order to proceed
further. If false is returned by cv then
that thread will release the mutex
(mtx) and wait for the condition to
become true.

1) Locked mutex (mtx) (line no.18)


2) Waiting by Releasing mtx (line no.19)
3) Once t2 thread acquire mtx it will add money
and notify to thread t1 and release mtx.
4) Thread t2 will acquire mtx and then if
balance was found greater then money
requested the transaction will happen.
Thanks for reading ❤

You might also like