Guest User

Untitled

a guest
Jul 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <sys/time.h>
  4. #include <time.h>
  5. #include <errno.h>
  6. #include <stdlib.h>
  7.  
  8. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  9. pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  10.  
  11. int g_ms = -1;
  12. int iterations = 0;
  13.  
  14. void waitMillis(int ms)
  15. {
  16. int n;
  17. struct timeval tv;
  18. struct timespec ts;
  19.  
  20. gettimeofday(&tv, NULL);
  21. ts.tv_sec = time(NULL) + ms / 1000;
  22. ts.tv_nsec = tv.tv_usec * 1000 + 1000 * 1000 * (ms % 1000);
  23. ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
  24. ts.tv_nsec %= (1000 * 1000 * 1000);
  25.  
  26. pthread_mutex_lock(&mutex);
  27. n = pthread_cond_timedwait(&cond, &mutex, &ts);
  28. pthread_mutex_unlock(&mutex);
  29.  
  30. if (n == 0) {
  31. printf("waitMillis: We were signalled!\n");
  32. } else if (n == ETIMEDOUT) {
  33. printf("waitMillis: We timed out!\n");
  34. }
  35. }
  36.  
  37. void *threadRoutine(void *arg) {
  38. while (1) {
  39. waitMillis(g_ms);
  40. iterations++;
  41. printf("threadRoutine: Finished (%d)\n", iterations);
  42. }
  43. }
  44.  
  45. int main(int argc, const char **argv) {
  46. pthread_t thread;
  47. int input, ms;
  48.  
  49. if (argc < 2) {
  50. fprintf(stderr, "Error: Please pass milliseconds for our timer!\n");
  51. exit(-1);
  52. }
  53.  
  54. ms = atoi(argv[1]);
  55. if (ms < 100) {
  56. fprintf(stderr, "Error: Pas at least 100ms!\n");
  57. exit(-1);
  58. }
  59.  
  60. g_ms = ms;
  61. pthread_create(&thread, NULL, threadRoutine, NULL);
  62.  
  63. while (1) {
  64. printf("Main: Enter a number\n");
  65. scanf(" %d", &input);
  66. if (input == 0) {
  67. printf("Main: Signalling thread...\n");
  68. pthread_cond_signal(&cond);
  69. } else {
  70. printf("Main: Not signalling\n");
  71. }
  72. }
  73. }
Add Comment
Please, Sign In to add comment