![]() |
VOOZH | about |
Multithreading is a technique where a process is divided into multiple threads that can run concurrently. It is used to perform multiple tasks efficiently within a single program.
In C programming language, we use the POSIX Threads (pthreads) library to implement multithreading, which provides different components along with thread management functions that create the foundation of a multithreaded program in C.
The pthread library is defined inside <pthread.h> header file. Generally, we don't need to explicity specify to the linker that we are using this library but if the program shows error, then compile it with the following flags:
Below is the demonstration of how to perform multithreading in C program.
The first step is to create a thread and give it a task. To create a new thread, we use the pthread_create() function provided by the thread library in C. It initializes and starts the thread to run the given function (which specifies its task).
Syntax
where,
The following program demonstrates thread creation and execution
Output
Created a new thread
In the above program, there is a possibility that the main thread may end before the execution of the created thread thread1 and it may lead to unexpected behaviour of the program. So, there is a functionality in C to wait for the execution of the particular thread.
pthread_join() function allows one thread to wait for the termination of another thread. It is used to synchronize the execution of threads. Example:
Output
Thread is running
pthread_exit() function allows a thread to terminate its execution explicitly. pthread_exit() is called when a thread needs to terminate its execution and optionally return a value to threads that are waiting for it. Example:
Output
Thread is running.
The pthread_cancel() function is used to request the cancellation of a thread. It sends a cancellation request to the target thread, but the actual termination depends on whether the thread is in a cancellable state and if it handles cancellation. Example:
Output
Thread is running...
Thread is running...
Thread is running...
Thread is running...
Thread is running...
Thread is running...
Main thread finished.
pthread_self() function returns the thread ID of the calling thread. This is useful when you need to identify or store the ID of the current thread in multi-threaded programs. Example
Output
Current thread ID: 134681321096896
Multithreading can greatly improve the performance of the program by running multiple tasks simultaneously. But it also comes with several threading issues and challenges that need to be handled properly to ensure efficient running of a multithreaded program Some of the common issues in multithreading in c are as follows:
The race condition issue occurs when multiple threads try to access a shared resource at the same time and the output depends on the order of the execution of those threads. This issue can lead to unpredictable behavior of the program and cause the program to generate different results each time when it is executed.
Example: If two threads try to access a shared counter variable where both are trying to change the value based on the current value, then the program may not generate the expected result because both threads may read and write the counter at the same time.
A deadlock condition arises when multiple threads are blocked forever as they are waiting for each other to release the occupied resource. It generally arises in situations where thread acquire some resources initially and request for more resources midway during their execution. Which leads to a cycle of dependencies.
Example: Thread A has occupied Resource 1 and 2 are waiting for resource 3 while thread B has occupied resource 3 and is waiting for resource 2 for its completion.
The starvation condition arises when a thread is denied access for the requested resource for indefinite amount of time. This situation commonly occurs with priority-based scheduling algorithms when they are biased toward certain threads.
Example: A thread with low priority will have to wait indefinitely as higher priority threads are continuously available.
Thread synchronization is a process that is used to ensure that multiple threads can work with shared resources without causing any issues like race conditions, deadlocks, or data corruption. Thread synchronisation techniques control how threads interact or modify shared data or resources and also ensures that certain critical sections of code are executed in a controlled manner.
Multithreading is used to improve a program’s efficiency by allowing it to perform multiple tasks in parallel. It enhances CPU utilization, reduces idle time, and makes applications faster and more responsive, especially in tasks like file handling, user interaction, and background processing.
For example, in a browser, multiple tabs can be different threads. MS Word uses multiple threads: one thread to format the text, another thread to process inputs, etc.