chan.c
Upload User: shmaik
Upload Date: 2014-06-01
Package Size: 45093k
Code Size: 1k
Development Platform:

C/C++

  1. static char rcsid[] = "$Id: H:/drh/idioms/book/RCS/thread.doc,v 1.11 1997/02/21 19:50:51 drh Exp $";
  2. #include <string.h>
  3. #include "assert.h"
  4. #include "mem.h"
  5. #include "chan.h"
  6. #include "sem.h"
  7. #define T Chan_T
  8. struct T {
  9. const void *ptr;
  10. int *size;
  11. Sem_T send, recv, sync;
  12. };
  13. T Chan_new(void) {
  14. T c;
  15. NEW(c);
  16. Sem_init(&c->send, 1);
  17. Sem_init(&c->recv, 0);
  18. Sem_init(&c->sync, 0);
  19. return c;
  20. }
  21. int Chan_send(Chan_T c, const void *ptr, int size) {
  22. assert(c);
  23. assert(ptr);
  24. assert(size >= 0);
  25. Sem_wait(&c->send);
  26. c->ptr = ptr;
  27. c->size = &size;
  28. Sem_signal(&c->recv);
  29. Sem_wait(&c->sync);
  30. return size;
  31. }
  32. int Chan_receive(Chan_T c, void *ptr, int size) {
  33. int n;
  34. assert(c);
  35. assert(ptr);
  36. assert(size >= 0);
  37. Sem_wait(&c->recv);
  38. n = *c->size;
  39. if (size < n)
  40. n = size;
  41. *c->size = n;
  42. if (n > 0)
  43. memcpy(ptr, c->ptr, n);
  44. Sem_signal(&c->sync);
  45. Sem_signal(&c->send);
  46. return n;
  47. }