Threads
23BAI1229
Shobhit Singh
1. Create a thread pass string as your name to the thread and also print your registration
number to main thread and print their IDs.
Output:
2. Create two threads and display the two different function ( Addition/ Odd or even ete.,) along
with the corresponding thread_id. (pthread_self() function returns thread id)
Output:
3. Design two threads to count the vowels and consonants either from text file or a given
string.
Output:
4. (i)Write a program to sum up an array of 1000000 elements where elements are
consecutive natural numbers.
Output:
(ii) Create two or four threads for splitting the sum and find the execution time.
Output:
(iii)Analyse and comment on the execution time and justify the need of multithreaded
programming.
ANS: Multithreading helps reduce execution time by dividing a task among multiple threads. In a
single-threaded approach, the entire array is processed sequentially, which takes more time. By
using multiple threads, each one handles a portion of the array in parallel, significantly cutting down
the time required. For example, with two threads, the execution time is almost halved, while four
threads can reduce it further, though the benefit depends on the number of available CPU cores.
The main advantages of multithreading are faster performance, better resource utilization,
scalability, and improved responsiveness. Threads can run simultaneously on multiple CPU cores,
making the most of available hardware. This is especially useful for handling larger tasks by
splitting the workload.
Additionally, multithreading allows background tasks to run without
blocking the main program, improving the responsiveness of applications.
In summary, multithreading can greatly enhance performance by processing tasks in parallel.
However, it should be applied when the performance gains outweigh the overhead associated with
managing multiple threads.