Sin descripción
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-two-cvs-while.c 2.1KB

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