File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
4-Multithreaded programming/pthreads Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments