Multithreading in C++ by Mandeep Punia
Multithreading in C++ by Mandeep Punia
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:
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.
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.
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
SYNTAX: std::try_lock(m1,m2,m3,m4….,mn);
3) If it fails to lock any of the mutex then it will release all the mutex it
locked before
1) notify_one()
2) notify_all()