You are on page 1of 5

Exp No: Threading & Synchronization

Applications

AIM:
To execute a C program implementing threading and synchronization applications.

Threading and Synchronization:


Threading allows multiple threads of execution to run concurrently within a single process.
Synchronization refers to the coordination of the execution of threads in order to avoid race
conditions and other problems that can occur when multiple threads access shared resources
simultaneously.

Algorithm:
1. Declare and initialize global variables `counter`, `a`, and `b`.
2. Define function `doSomeThing1` to print values of `a` 5000 times.
3. Define function `doSomeThing2` to print values of `b` 5000 times.
4. Call `pthread_create` twice to create threads for `doSomeThing1` and `doSomeThing2`.
5. Check for errors in the thread creation process.
6. Call `pthread_join` twice to wait for both threads to finish.
7. Print message indicating that both threads have finished.
8. Return 0 from the `main` function.
9. Compile and run the code.
10. Verify that the output shows the values of `a` and `b` being printed 5000 times each.

Code:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>
pthread_t tid[2];
int counter,a=1,b=1;
void* doSomeThing1(void *arg)
{
unsigned long i = 0;
printf("\n Job 1 started\n");
for(i=0; i<5000;i++)
printf("%d\n",a++);
printf("\n Job 1 finished\n");
return NULL;
}
void* doSomeThing2(void *arg)
{
unsigned long i = 0;
printf("\n Job 2 started\n");
for(i=0; i<5000;i++)
printf("%d\n",b++);
printf("\n Job 2 finished\n");
return NULL;
}

int main(void)
{
int err1,err2;
err1 = pthread_create(&(tid[0]), NULL, &doSomeThing1, NULL);
if (err1 != 0)
printf ("\ncan't create thread :[%s]", strerror(err1));

err2 = pthread_create(&(tid[1]), NULL, &doSomeThing2, NULL);


if (err2 != 0)
printf ("\ncan't create thread :[%s]", strerror(err2));
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}

Output:
Result:
Thus the C program implementing Threading and synchronization was written,executed and the
outputs are verified.

You might also like