Ex - No.5 Threads Questions
Ex - No.5 Threads Questions
5 MULTI-THREADING
AIM:
Write a C program to demonstrate various thread related concepts.
Threads:
A thread is a path which is followed during a program’s execution. Majority of programs written now
a days run as a single thread. Let’s say, for example a program is not capable of reading keystrokes
while making drawings. These tasks cannot be executed by the program at the same time. This
problem can be solved through multitasking so that two or more tasks can be executed
simultaneously.
Multitasking is of two types: Processor based and thread based. Processor based multitasking is
totally managed by the OS, however multitasking through multithreading can be controlled by the
programmer to some extent.
The concept of multi-threading needs proper understanding of these two terms – a process and a
thread. A process is a program being executed. A process can be further divided into independent units
known as threads.
A thread is like a small light-weight process within a process. Or we can say a collection of threads is
what is known as a process.
Why Multithreading? Threads are popular way to improve application through parallelism.
For example, in a browser, multiple tabs can be different threads. MS word uses multiple
threads, one thread to format the text, other thread to process inputs, etc.
Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or Pthreads)
is a POSIX standard for threads. Implementation of pthread is available with gcc compiler.
We must include the pthread.h header file at the beginning of the script to use all the
functions of the pthreads library.
Create 3 threads, first one to find the sum of odd numbers; second one to find the sum of even
numbers; third one to find the sum of natural numbers;
This program also displays the list of odd/even numbers.
Complete the code snippet wherever applicable in the below program highlighted in red colour
font.
int je,jo,evensum=0,sumn=0,oddsum=0,evenarr[50],oddarr[50];
for(i=0;i<=n;i++)
{
if(logic to allow only odd numbers)
{Calculate sum of odd numbers only}
}
}
void *SumN(_________)
{
int i,n;
n=(int)threadid;
for(i=1;i<=n;i++)
{ Calculate sum of natural numbers only}
}
int main()
{
pthread_t threads[NUM_THREADS];
int i,t;
printf("Enter a number\n");
scanf("%d",&t);
for(i=0;i<NUM_THREADS;i++)
{
pthread_join(threads[i],NULL);
}
printf("The sum of first N natural numbers is %d\n", display the sum of natural numbers);
printf("The sum of first N even numbers is %d\n",display the sum of even numbers);
printf("The sum of first N odd numbers is %d\n",oddsum);
printf("The first N Even numbers are----\n");
Print all the Even numbers
printf("The first N Odd numbers are ----\n");
Print all the ODD numbers
pthread_exit(NULL);
}
Result:
Thus, the program has been executed successfully by creating three threads.