Modify the code so that:
- Each thread's static storage (i.e., Thread Specific Storage) keeps
both its error count and the thread's name;
- When an FPE trap is fired, the thread display's its name and
current error count.(hint: use a structure).
Questions:
Normally a process has one set of handlers and one thread, so
what should de done for a multithreaded process when it fires a trap?
Should a new thread be created, use the main thread, or what option (s)
are (reasonably) possible?
|
- #define
_REENTRANT_
/* a flag */
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <signal.h>
- #include <thread.h>
- #include <setjmp.h>
-
- thread_key_t errorkey; /*
key to access the Thread Specific Storage */
-
- sigjmp_buf sjbuf;
-
- void grace(int );
-
- void * foo(void *datum)
- {int x,y,z;
- int *error_count;
- thr_getspecific(errorkey, ( void *) &error_count);
- if
( error_count == NULL) {
-
error_count = (int *) malloc( sizeof(int) );
-
thr_setspecific(errorkey, (int *) error_count);
-
*error_count = 0;
- }
-
- sigset( SIGFPE, grace); /* establish handler */
- while (1) {
- if (sigsetjmp(sjbuf,1) == 0)
- {
- // sigsetjmp(sjbuf,1 ); /* remember this point */
- x = rand()%5;
- y = rand()%5;
- z = x / y;
- printf("thread %s has computed
%d=%d/%d\n", (char *) datum, z,x,y);
- }
- }
- printf("error_count points to :=== %x\n",
*error_count);
- }
- void _doom(void * S) /* destructor automatically
called and given the */
- { /* slot contents */
- free( S );
- }
- #define NTHR 2
- #define MAX_TRIES 3
- char *name[] = { "Ali",
- "Doug",
- "Yoon",
- "" /* NULL string */
- };
- int error_count_int=0;
- void main(void)
- { int i=0;
- thread_t thr[NTHR];
- thr_keycreate(&errorkey, &_doom);
- for(i=0; i<NTHR; i++)
- {
- thr_create(NULL, NTHR , foo(name[i]), (void *)
name[i], THR_BOUND, &thr[i]);
- printf(" THR_BOUND :=== %x\n", THR_BOUND);
- }
- while ( thr_join(thr[1], thr, NULL) == 0);
- foo(name[i]);
- }
- void grace(int sig) /* signal handler */
- { void *error_count=NULL;
- thr_getspecific(errorkey, (void *) &error_count);
- error_count_int = (int *) error_count;
- printf("\n error_count_int :=== %d \n",
error_count_int);
- error_count_int++;
- if ( (error_count_int) > MAX_TRIES) {
- printf("Thread exceeds max error
attempts\n");
- thr_exit(0);
- }
- else { /* try again */
- printf("Aborting current computation\n");
- siglongjmp( sjbuf, 1);
- }
- }
|