Ei kuvausta
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main-one-cv-while.c 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <ctype.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <assert.h>
  6. #include <pthread.h>
  7. #include <sys/time.h>
  8. #include <string.h>
  9. #include "mythreads.h"
  10. #include "pc-header.h"
  11. pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
  12. pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
  13. #include "main-header.h"
  14. void do_fill(int value) {
  15. // ensure empty before usage
  16. ensure(buffer[fill_ptr] == EMPTY, "error: tried to fill a non-empty buffer");
  17. buffer[fill_ptr] = value;
  18. fill_ptr = (fill_ptr + 1) % max;
  19. num_full++;
  20. }
  21. int do_get() {
  22. int tmp = buffer[use_ptr];
  23. ensure(tmp != EMPTY, "error: tried to get an empty buffer");
  24. buffer[use_ptr] = EMPTY;
  25. use_ptr = (use_ptr + 1) % max;
  26. num_full--;
  27. return tmp;
  28. }
  29. void *producer(void *arg) {
  30. int id = (int) arg;
  31. // make sure each producer produces unique values
  32. int base = id * loops;
  33. int i;
  34. for (i = 0; i < loops; i++) { p0;
  35. Mutex_lock(&m); p1;
  36. while (num_full == max) { p2;
  37. Cond_wait(&cv, &m); p3;
  38. }
  39. do_fill(base + i); p4;
  40. Cond_signal(&cv); p5;
  41. Mutex_unlock(&m); p6;
  42. }
  43. return NULL;
  44. }
  45. void *consumer(void *arg) {
  46. int id = (int) arg;
  47. int tmp = 0;
  48. int consumed_count = 0;
  49. while (tmp != END_OF_STREAM) { c0;
  50. Mutex_lock(&m); c1;
  51. while (num_full == 0) { c2;
  52. Cond_wait(&cv, &m); c3;
  53. }
  54. tmp = do_get(); c4;
  55. Cond_signal(&cv); c5;
  56. Mutex_unlock(&m); c6;
  57. consumed_count++;
  58. }
  59. // return consumer_count-1 because END_OF_STREAM does not count
  60. return (void *) (long long) (consumed_count - 1);
  61. }
  62. // must set these appropriately to use "main-common.c"
  63. pthread_cond_t *fill_cv = &cv;
  64. pthread_cond_t *empty_cv = &cv;
  65. // all codes use this common base to start producers/consumers
  66. // and all the other related stuff
  67. #include "main-common.c"