/** * A pthread program illustrating how to * create a simple thread and some of the pthread API * This program implements the summation function where * the summation operation is run as a separate thread. * * Most Unix/Linux/OS X users * gcc thrd.c -lpthread * * Solaris users must enter * gcc thrd.c -lpthreads * * Figure 4.9 * * @author Gagne, Galvin, Silberschatz * Operating System Concepts - Ninth Edition * Copyright John Wiley & Sons - 2013 * * Revised X. Meng * 09-11-2013 * to display the values of attributes */ #include #include int sum; /* this data is shared by the thread(s) */ void *runner(void *param); /* the thread */ void display_attr(pthread_attr_t attr); /* display attribute values */ int main(int argc, char *argv[]) { pthread_t tid; /* the thread identifier */ pthread_attr_t attr; /* set of attributes for the thread */ if (argc != 2) { fprintf(stderr,"usage: %s \n", argv[0]); /*exit(1);*/ return -1; } if (atoi(argv[1]) < 0) { fprintf(stderr,"Argument %d must be non-negative\n",atoi(argv[1])); /*exit(1);*/ return -1; } /* get the default attributes */ pthread_attr_init(&attr); /* create the thread */ pthread_create(&tid,&attr,runner,argv[1]); /* * pthread_getattr_np() is a GNU extension to pthread, non-standard. * This function retrieves attributes that include stack information */ pthread_getattr_np(pthread_self(), &attr); /* display various attribute default values */ display_attr(attr); /* now wait for the thread to exit */ pthread_join(tid,NULL); printf("sum = %d\n",sum); return 0; } /** * The thread will begin control in this function */ void *runner(void *param) { int i, upper = atoi(param); sum = 0; if (upper > 0) { for (i = 1; i <= upper; i++) sum += i; } pthread_exit(0); } void display_attr(pthread_attr_t attr) { int s, i; struct sched_param sp; size_t v; void *stkaddr; pthread_t tid = pthread_self(); printf("Attributes for thread %lu\n", tid); s = pthread_attr_getschedpolicy(&attr, &i); printf("Scheduling policy = %s\n", (i == SCHED_OTHER) ? "SCHED_OTHER" : (i == SCHED_FIFO) ? "SCHED_FIFO" : (i == SCHED_RR) ? "SCHED_RR" : "???"); s = pthread_attr_getschedparam(&attr, &sp); printf("Scheduling priority = %d\n", sp.sched_priority); s = pthread_attr_getstack(&attr, &stkaddr, &v); printf("Stack address = %p\n", stkaddr); printf("Stack size = 0x%x bytes\n", v); }