Advertisement
teknoraver

thread start/stop

May 8th, 2016
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.87 KB | None | 0 0
  1.  
  2. #define _GNU_SOURCE
  3.  
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <signal.h>
  7. #include <pthread.h>
  8.  
  9. pthread_t tid[2];
  10. pthread_mutex_t startlock;
  11. pthread_cond_t startcond;
  12.  
  13. #define START   1
  14. #define STOP    2
  15.  
  16. static void usr2 (int signum, siginfo_t *siginfo, void *context)
  17. {
  18.     sigset_t intmask;
  19.  
  20.     printf("T [%lu]: got signal%d\n", pthread_self(), signum);
  21.     sigemptyset(&intmask);
  22.     sigaddset(&intmask, signum);
  23.     sigprocmask(SIG_UNBLOCK, &intmask, NULL);
  24.  
  25.     if(siginfo->si_value.sival_int == STOP) {
  26.         pthread_mutex_init(&startlock, NULL);
  27.         pthread_cond_init(&startcond, NULL);
  28.         pthread_mutex_lock(&startlock);
  29.         pthread_cond_wait(&startcond, &startlock);
  30.         pthread_mutex_unlock(&startlock);
  31.     } else if(siginfo->si_value.sival_int == START) {
  32.         pthread_cond_signal(&startcond);
  33.     } else
  34.         printf("unknown action: %d\n", siginfo->si_value.sival_int);
  35. }
  36.  
  37. static void * t1(void *arg)
  38. {
  39.     for(int i = 0; ; i++) {
  40.         printf("T1[%lu]: %d\n", pthread_self(), i);
  41.         sleep(1);
  42.     }
  43.  
  44.     return NULL;
  45. }
  46.  
  47. static void * t2(void *arg)
  48. {
  49.     for(int i = 0; ; i++) {
  50.         printf("T2[%lu]: %d\n", pthread_self(), i);
  51.         sleep(1);
  52.         if(i == 1) {
  53.             printf("T2[%lu]: sending signal STOP\n", pthread_self());
  54.             pthread_sigqueue(tid[0], SIGUSR2, (union sigval)STOP);
  55.         } else if(i == 5) {
  56.             printf("T2[%lu]: sending signal START\n", pthread_self());
  57.             pthread_sigqueue(tid[0], SIGUSR2, (union sigval)START);
  58.         } else if(i == 8) {
  59.             printf("T2[%lu]: sending signal RANDOM\n", pthread_self());
  60.             pthread_sigqueue(tid[0], SIGUSR2, (union sigval)(int)(tid[0] * tid[1] >> 16 & 0xffff));
  61.         }
  62.     }
  63.  
  64.     return NULL;
  65. }
  66.  
  67. struct sigaction act = {
  68.     .sa_sigaction = usr2,
  69.     .sa_flags = SA_SIGINFO,
  70. };
  71.  
  72. int main(int argc, char *argv[])
  73. {
  74.     sigaction(SIGUSR2, &act, NULL);
  75.  
  76.     pthread_create(tid + 0, NULL, t1, 0);
  77.     pthread_create(tid + 1, NULL, t2, 0);
  78.  
  79.     while(1)
  80.         sleep(10);
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement