Skip to content

Commit 3df5dd9

Browse files
committed
Using Pthread library
1 parent 5962c36 commit 3df5dd9

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
8.91 KB
Binary file not shown.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <pthread.h>
2+
#include <stdio.h>
3+
4+
int sum; /* this data is shared by the threads */
5+
void *runner(void *param); /* threads call this function */
6+
7+
int main(int argc, char *argv[])
8+
{
9+
pthread_t tid; /* the thread identifier */
10+
pthread_attr_t attr; /* set of thread attributes */
11+
12+
if(argc != 2){
13+
fprintf(stderr, "usage: a.out <integer value>\n");
14+
return -1;
15+
}
16+
if(atoi(argv[1]) < 0){
17+
fprintf(stderr, "%d must be >=0\n", atoi(argv[1]));
18+
return -1;
19+
}
20+
21+
/* get the default attributes */
22+
pthread_attr_init(&attr);
23+
/* create the thread */
24+
pthread_create(&tid,&attr,runner,argv[1]);
25+
/* wait for the thread to exit */
26+
pthread_join(tid, NULL);
27+
28+
printf("sum = %d\n", sum);
29+
}
30+
31+
/* The thread will begin control in this function */
32+
void *runner(void *param){
33+
int i, upper = atoi(param);
34+
sum = 0;
35+
for(i = 1; i <= upper; i++)
36+
sum += i;
37+
38+
pthread_exit(0);
39+
}

0 commit comments

Comments
 (0)