-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththreadEx1.c
More file actions
39 lines (39 loc) · 1014 Bytes
/
Copy paththreadEx1.c
File metadata and controls
39 lines (39 loc) · 1014 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Program to create a thread.
// The thread prints numbers from zero to n,
// where value of n is passed from the main process
// to the thread. The main process also waits
// for the thread to finish first and then prints
// from 20-24.
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
void *thread_function(void *arg);
int i, n, j;
int main()
{
char *m = "5";
pthread_t a_thread; //thread declaration
void *result;
pthread_create(&a_thread,NULL,thread_function,m); //thread is created
pthread_join(a_thread,&result);//process waits for thread to finish. Comments this line to see the defferance
printf("Thread joined\n");
for(j=20;j<25;j++)
{
printf("%d\n",j);
sleep(1);
}
printf("thread returned %s\n",result);
}
void *thread_function(void *arg)//the work to be done by the thread is defined in the function
{
int sum = 0;
n = atoi(arg);
for(i=0;i<n;i++)
{
printf("%d\n",i);
sleep(1);
}
pthread_exit("Done");//thread returns "Done"
}