Guest User

pthread_getspecific in signal handler

a guest
Dec 14th, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.68 KB | None | 0 0
  1. #include <signal.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <pthread.h>
  5. #include <sys/time.h>
  6.  
  7. #define N 4
  8.  
  9. sig_atomic_t signal_count[N];
  10. pthread_key_t token;
  11.  
  12. long gettime ()
  13. {
  14.     struct timeval tv;
  15.     gettimeofday (&tv, 0);
  16.     return tv.tv_sec;
  17. }
  18.  
  19. void idle_time(int seconds)
  20. {
  21.     long start = gettime();
  22.     while(1)
  23.     {
  24.         if(gettime() > start + seconds)
  25.         {
  26.             break;
  27.         }
  28.     }
  29. }
  30.  
  31. static void sigprof_handler(int sig_nr, siginfo_t* info, void *context)
  32. {
  33.     sig_atomic_t *counter = pthread_getspecific (token);
  34.     if (counter)  *counter = *counter + 1;
  35. }
  36.  
  37. void* thread_work(void* data)
  38. {
  39.     pthread_setspecific (token, data);
  40.  
  41.     // Do work
  42.     idle_time (10);
  43.     return NULL;
  44. }
  45.  
  46. int main ()
  47. {
  48.     int i;
  49.     for (i = 0; i < N; i++) signal_count[i] = 0;
  50.  
  51.     struct sigaction sa;
  52.     sa.sa_sigaction = sigprof_handler;
  53.     sa.sa_flags = SA_RESTART | SA_SIGINFO;
  54.     sigemptyset(&sa.sa_mask);
  55.     sigaction(SIGPROF, &sa, NULL);
  56.  
  57.     pthread_key_create (&token, NULL);
  58.    
  59.     static struct itimerval timer;
  60.     timer.it_interval.tv_sec = 0;
  61.     timer.it_interval.tv_usec = 1000000 / 1000; /* 1000hz */
  62.     timer.it_value = timer.it_interval;
  63.     setitimer(ITIMER_PROF, &timer, NULL);
  64.  
  65.     pthread_t threads[N];
  66.     for(i = 0; i < N; i++)
  67.     {
  68.         pthread_create(&threads[i], NULL, thread_work, &(signal_count[i]));
  69.     }
  70.    
  71.     for(i = 0; i < N; i++)
  72.     {
  73.         pthread_join(threads[i], NULL);
  74.     }
  75.    
  76.     for(i = 0; i < N; i++)
  77.     {
  78.         printf("Signals caught after %dx10 seconds by thread %d: %ld \n", N, i, signal_count[i]);
  79.     }
  80.    
  81.     pthread_key_delete (token);
  82. }
Advertisement
Add Comment
Please, Sign In to add comment