Professional Documents
Culture Documents
Applications
AIM:
To execute a C program implementing threading and synchronization applications.
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));
Output:
Result:
Thus the C program implementing Threading and synchronization was written,executed and the
outputs are verified.