How to manage Threads in C++ programming?
Threads are handled by using built-in functions in C++. The header file needed is ‘<thread>’. It has the following functions as follows….
‘get_id()’ – it is used to get the id of the current thread.
It is used for logging and debugging.
‘hardware_concurrency()’
- Returns the number of hardware threads available for use.
‘detach()’ – it allows the thread to run independently.
‘join()’ – it makes the calling thread to complete the
execution.
‘mutex()’ -it is used to deal with shared data.
‘atomic()’ – it is useful to manage the threads in safe
manner.
‘sleep_for()’- pauses the execution for specified time.
‘sleep_until()’-pauses the execution for time until the
specified time.
‘lock_guard()’ – it locks
and unlocks the thread in mutex block.
‘condition_variable’ -it
is used to synchronize the threads.
What are the problems in Multithreading?
when
multiple threads are running at a time,it improves the performance. But it also
has some problems.
Race condition – when two or more threads access a same
resource at same time, it happens.
Deadlock – it happens when some threads are waiting and one
thread is using the resource long time.
Starvation – when a particular thread is unable to share a resource
while others use it long time.
These are the problems in multi threading. The solution is
given below.
Solution:
It is a process to synchronize
the threads. It makes the thread to run at a time.This uses mutexes, locks, and
condition variables for achieving this.
It makes
the thread to stop its execution and starts other thread’s execution based on situation.
Here, the state of thread is stored and retrieved during execution.
These are the ways to manage threads. You can use the built
-in functions in c++ to handle the multithreading effectively.
Comments
Post a Comment