semacquire 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. .TH SEMACQUIRE 2
  2. .SH NAME
  3. semacquire, semrelease \- user level semaphores
  4. .SH SYNOPSIS
  5. .B #include <u.h>
  6. .br
  7. .B #include <libc.h>
  8. .PP
  9. .B
  10. int semacquire(long *addr, int block);
  11. .PP
  12. .B
  13. long semrelease(long *addr, long count);
  14. .SH DESCRIPTION
  15. .I Semacquire
  16. and
  17. .I semrelease
  18. facilitate scheduling between processes sharing memory.
  19. Processes arrange to share memory by using
  20. .I rfork
  21. with the
  22. .B RFMEM
  23. flag
  24. (see
  25. .IR fork (2)),
  26. .IR segattach (2),
  27. or
  28. .IR thread (2).
  29. .PP
  30. The semaphore's value is the integer pointed at by
  31. .IR addr .
  32. .I Semacquire
  33. atomically waits until the semaphore has a positive value
  34. and then decrements that value.
  35. It returns 1 if the semaphore was acquired and \-1 on error
  36. (e.g., if it was interrupted).
  37. If
  38. .I block
  39. is zero
  40. and the semaphore is not immediately available,
  41. .I semacquire
  42. returns 0 instead of waiting.
  43. .I Semrelease
  44. adds
  45. .I count
  46. to the semaphore's value
  47. and returns the new value.
  48. .PP
  49. .I Semacquire
  50. and
  51. .I semrelease
  52. can be thought of as efficient, correct replacements for:
  53. .IP
  54. .EX
  55. int
  56. semacquire(long *addr, int block)
  57. {
  58. while(*addr == 0){
  59. if(!block)
  60. return 0;
  61. if(interrupted)
  62. return -1;
  63. }
  64. --*addr;
  65. return 1;
  66. }
  67. int
  68. semrelease(long *addr, int count)
  69. {
  70. return *addr += count;
  71. }
  72. .EE
  73. .PP
  74. Like
  75. .IR rendezvous (2),
  76. .I semacquire
  77. and
  78. .I semrelease
  79. are not typically used directly.
  80. Instead, they are intended to be used to coordinate
  81. scheduling in higher-level abstractions such as
  82. locks, rendezvous points, and channels
  83. (see
  84. .IR lock (2)
  85. and
  86. .IR thread (2)).
  87. Also like
  88. .I rendezvous ,
  89. .I semacquire
  90. and
  91. .I semrelease
  92. cannot be used to coordinate between threads
  93. in a single process.
  94. Use locks, rendezvous points, or channels instead.
  95. .SH SOURCE
  96. .B /sys/src/9/port/sysproc.c
  97. .SH SEE ALSO
  98. .IR fork (2),
  99. .IR lock (2),
  100. .IR rendezvous (2),
  101. .IR segattach (2),
  102. .IR thread (2)
  103. .SH DIAGNOSTICS
  104. These functions set
  105. .IR errstr .