tfifo.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /*
  2. tfifo.c
  3. David Rowe
  4. Nov 19 2012
  5. Takes FIFOs, in particular thread safety.
  6. */
  7. #include <assert.h>
  8. #include <stdio.h>
  9. #include <pthread.h>
  10. #include "fifo.h"
  11. #define FIFO_SZ 1024
  12. #define WRITE_SZ 10
  13. #define READ_SZ 8
  14. #define N_MAX 100
  15. #define LOOPS 1000000
  16. int run_thread = 1;
  17. struct FIFO *f;
  18. void writer(void);
  19. void *writer_thread(void *data);
  20. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  21. #define USE_THREADS
  22. //#define USE_MUTEX
  23. int main() {
  24. pthread_t awriter_thread;
  25. int i,j;
  26. short read_buf[READ_SZ];
  27. int n_out = 0;
  28. int sucess;
  29. f = fifo_create(FIFO_SZ);
  30. #ifdef USE_THREADS
  31. pthread_create(&awriter_thread, NULL, writer_thread, NULL);
  32. #endif
  33. for(i=0; i<LOOPS; ) {
  34. #ifndef USE_THREADS
  35. writer();
  36. #endif
  37. #ifdef USE_MUTEX
  38. pthread_mutex_lock(&mutex);
  39. #endif
  40. sucess = (fifo_read(f, read_buf, READ_SZ) == 0);
  41. #ifdef USE_MUTEX
  42. pthread_mutex_unlock(&mutex);
  43. #endif
  44. if (sucess) {
  45. for(j=0; j<READ_SZ; j++) {
  46. if (read_buf[j] != n_out)
  47. printf("error: %d %d\n", read_buf[j], n_out);
  48. n_out++;
  49. if (n_out == N_MAX)
  50. n_out = 0;
  51. }
  52. i++;
  53. }
  54. }
  55. #ifdef USE_THREADS
  56. run_thread = 0;
  57. pthread_join(awriter_thread,NULL);
  58. #endif
  59. return 0;
  60. }
  61. int n_in = 0;
  62. void writer(void) {
  63. short write_buf[WRITE_SZ];
  64. int i;
  65. if ((FIFO_SZ - fifo_used(f)) > WRITE_SZ) {
  66. for(i=0; i<WRITE_SZ; i++) {
  67. write_buf[i] = n_in++;
  68. if (n_in == N_MAX)
  69. n_in = 0;
  70. }
  71. #ifdef USE_MUTEX
  72. pthread_mutex_lock(&mutex);
  73. #endif
  74. fifo_write(f, write_buf, WRITE_SZ);
  75. pthread_mutex_unlock(&mutex);
  76. }
  77. }
  78. void *writer_thread(void *data) {
  79. while(run_thread) {
  80. writer();
  81. }
  82. return NULL;
  83. }