Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <signal.h>
- #include <stdio.h>
- #include <string.h>
- #include <pthread.h>
- #include <sys/time.h>
- #define N 4
- sig_atomic_t signal_count[N];
- pthread_key_t token;
- long gettime ()
- {
- struct timeval tv;
- gettimeofday (&tv, 0);
- return tv.tv_sec;
- }
- void idle_time(int seconds)
- {
- long start = gettime();
- while(1)
- {
- if(gettime() > start + seconds)
- {
- break;
- }
- }
- }
- static void sigprof_handler(int sig_nr, siginfo_t* info, void *context)
- {
- sig_atomic_t *counter = pthread_getspecific (token);
- if (counter) *counter = *counter + 1;
- }
- void* thread_work(void* data)
- {
- pthread_setspecific (token, data);
- // Do work
- idle_time (10);
- return NULL;
- }
- int main ()
- {
- int i;
- for (i = 0; i < N; i++) signal_count[i] = 0;
- struct sigaction sa;
- sa.sa_sigaction = sigprof_handler;
- sa.sa_flags = SA_RESTART | SA_SIGINFO;
- sigemptyset(&sa.sa_mask);
- sigaction(SIGPROF, &sa, NULL);
- pthread_key_create (&token, NULL);
- static struct itimerval timer;
- timer.it_interval.tv_sec = 0;
- timer.it_interval.tv_usec = 1000000 / 1000; /* 1000hz */
- timer.it_value = timer.it_interval;
- setitimer(ITIMER_PROF, &timer, NULL);
- pthread_t threads[N];
- for(i = 0; i < N; i++)
- {
- pthread_create(&threads[i], NULL, thread_work, &(signal_count[i]));
- }
- for(i = 0; i < N; i++)
- {
- pthread_join(threads[i], NULL);
- }
- for(i = 0; i < N; i++)
- {
- printf("Signals caught after %dx10 seconds by thread %d: %ld \n", N, i, signal_count[i]);
- }
- pthread_key_delete (token);
- }
Advertisement
Add Comment
Please, Sign In to add comment