channels.nim 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Channel support for threads. **Note**: This is part of the system module.
  10. ## Do not import it directly. To activate thread support you need to compile
  11. ## with the ``--threads:on`` command line switch.
  12. ##
  13. ## **Note:** The current implementation of message passing does
  14. ## not work with cyclic data structures.
  15. ## **Note:** Channels cannot be passed between threads. Use globals or pass
  16. ## them by `ptr`.
  17. when not declared(NimString):
  18. {.error: "You must not import this module explicitly".}
  19. type
  20. pbytes = ptr array[0.. 0xffff, byte]
  21. RawChannel {.pure, final.} = object ## msg queue for a thread
  22. rd, wr, count, mask, maxItems: int
  23. data: pbytes
  24. lock: SysLock
  25. cond: SysCond
  26. elemType: PNimType
  27. ready: bool
  28. region: MemRegion
  29. PRawChannel = ptr RawChannel
  30. LoadStoreMode = enum mStore, mLoad
  31. Channel* {.gcsafe.}[TMsg] = RawChannel ## a channel for thread communication
  32. const ChannelDeadMask = -2
  33. proc initRawChannel(p: pointer, maxItems: int) =
  34. var c = cast[PRawChannel](p)
  35. initSysLock(c.lock)
  36. initSysCond(c.cond)
  37. c.mask = -1
  38. c.maxItems = maxItems
  39. proc deinitRawChannel(p: pointer) =
  40. var c = cast[PRawChannel](p)
  41. # we need to grab the lock to be safe against sending threads!
  42. acquireSys(c.lock)
  43. c.mask = ChannelDeadMask
  44. deallocOsPages(c.region)
  45. deinitSys(c.lock)
  46. deinitSysCond(c.cond)
  47. proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel,
  48. mode: LoadStoreMode) {.benign.}
  49. proc storeAux(dest, src: pointer, n: ptr TNimNode, t: PRawChannel,
  50. mode: LoadStoreMode) {.benign.} =
  51. var
  52. d = cast[ByteAddress](dest)
  53. s = cast[ByteAddress](src)
  54. case n.kind
  55. of nkSlot: storeAux(cast[pointer](d +% n.offset),
  56. cast[pointer](s +% n.offset), n.typ, t, mode)
  57. of nkList:
  58. for i in 0..n.len-1: storeAux(dest, src, n.sons[i], t, mode)
  59. of nkCase:
  60. copyMem(cast[pointer](d +% n.offset), cast[pointer](s +% n.offset),
  61. n.typ.size)
  62. var m = selectBranch(src, n)
  63. if m != nil: storeAux(dest, src, m, t, mode)
  64. of nkNone: sysAssert(false, "storeAux")
  65. proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel,
  66. mode: LoadStoreMode) =
  67. template `+!`(p: pointer; x: int): pointer =
  68. cast[pointer](cast[int](p) +% x)
  69. var
  70. d = cast[ByteAddress](dest)
  71. s = cast[ByteAddress](src)
  72. sysAssert(mt != nil, "mt == nil")
  73. case mt.kind
  74. of tyString:
  75. if mode == mStore:
  76. var x = cast[PPointer](dest)
  77. var s2 = cast[PPointer](s)[]
  78. if s2 == nil:
  79. x[] = nil
  80. else:
  81. var ss = cast[NimString](s2)
  82. var ns = cast[NimString](alloc(t.region, ss.len+1 + GenericSeqSize))
  83. copyMem(ns, ss, ss.len+1 + GenericSeqSize)
  84. x[] = ns
  85. else:
  86. var x = cast[PPointer](dest)
  87. var s2 = cast[PPointer](s)[]
  88. if s2 == nil:
  89. unsureAsgnRef(x, s2)
  90. else:
  91. let y = copyDeepString(cast[NimString](s2))
  92. #echo "loaded ", cast[int](y), " ", cast[string](y)
  93. unsureAsgnRef(x, y)
  94. dealloc(t.region, s2)
  95. of tySequence:
  96. var s2 = cast[PPointer](src)[]
  97. var seq = cast[PGenericSeq](s2)
  98. var x = cast[PPointer](dest)
  99. if s2 == nil:
  100. if mode == mStore:
  101. x[] = nil
  102. else:
  103. unsureAsgnRef(x, nil)
  104. else:
  105. sysAssert(dest != nil, "dest == nil")
  106. if mode == mStore:
  107. x[] = alloc0(t.region, seq.len *% mt.base.size +% GenericSeqSize)
  108. else:
  109. unsureAsgnRef(x, newSeq(mt, seq.len))
  110. var dst = cast[ByteAddress](cast[PPointer](dest)[])
  111. var dstseq = cast[PGenericSeq](dst)
  112. dstseq.len = seq.len
  113. dstseq.reserved = seq.len
  114. for i in 0..seq.len-1:
  115. storeAux(
  116. cast[pointer](dst +% i*% mt.base.size +% GenericSeqSize),
  117. cast[pointer](cast[ByteAddress](s2) +% i *% mt.base.size +%
  118. GenericSeqSize),
  119. mt.base, t, mode)
  120. if mode != mStore: dealloc(t.region, s2)
  121. of tyObject:
  122. if mt.base != nil:
  123. storeAux(dest, src, mt.base, t, mode)
  124. else:
  125. # copy type field:
  126. var pint = cast[ptr PNimType](dest)
  127. pint[] = cast[ptr PNimType](src)[]
  128. storeAux(dest, src, mt.node, t, mode)
  129. of tyTuple:
  130. storeAux(dest, src, mt.node, t, mode)
  131. of tyArray, tyArrayConstr:
  132. for i in 0..(mt.size div mt.base.size)-1:
  133. storeAux(cast[pointer](d +% i*% mt.base.size),
  134. cast[pointer](s +% i*% mt.base.size), mt.base, t, mode)
  135. of tyRef, tyOptAsRef:
  136. var s = cast[PPointer](src)[]
  137. var x = cast[PPointer](dest)
  138. if s == nil:
  139. if mode == mStore:
  140. x[] = nil
  141. else:
  142. unsureAsgnRef(x, nil)
  143. else:
  144. #let size = if mt.base.kind == tyObject: cast[ptr PNimType](s)[].size
  145. # else: mt.base.size
  146. if mode == mStore:
  147. let dyntype = when declared(usrToCell): usrToCell(s).typ
  148. else: mt
  149. let size = dyntype.base.size
  150. # we store the real dynamic 'ref type' at offset 0, so that
  151. # no information is lost
  152. let a = alloc0(t.region, size+sizeof(pointer))
  153. x[] = a
  154. cast[PPointer](a)[] = dyntype
  155. storeAux(a +! sizeof(pointer), s, dyntype.base, t, mode)
  156. else:
  157. let dyntype = cast[ptr PNimType](s)[]
  158. var obj = newObj(dyntype, dyntype.base.size)
  159. unsureAsgnRef(x, obj)
  160. storeAux(x[], s +! sizeof(pointer), dyntype.base, t, mode)
  161. dealloc(t.region, s)
  162. else:
  163. copyMem(dest, src, mt.size) # copy raw bits
  164. proc rawSend(q: PRawChannel, data: pointer, typ: PNimType) =
  165. ## adds an `item` to the end of the queue `q`.
  166. var cap = q.mask+1
  167. if q.count >= cap:
  168. # start with capacity for 2 entries in the queue:
  169. if cap == 0: cap = 1
  170. var n = cast[pbytes](alloc0(q.region, cap*2*typ.size))
  171. var z = 0
  172. var i = q.rd
  173. var c = q.count
  174. while c > 0:
  175. dec c
  176. copyMem(addr(n[z*typ.size]), addr(q.data[i*typ.size]), typ.size)
  177. i = (i + 1) and q.mask
  178. inc z
  179. if q.data != nil: dealloc(q.region, q.data)
  180. q.data = n
  181. q.mask = cap*2 - 1
  182. q.wr = q.count
  183. q.rd = 0
  184. storeAux(addr(q.data[q.wr * typ.size]), data, typ, q, mStore)
  185. inc q.count
  186. q.wr = (q.wr + 1) and q.mask
  187. proc rawRecv(q: PRawChannel, data: pointer, typ: PNimType) =
  188. sysAssert q.count > 0, "rawRecv"
  189. dec q.count
  190. storeAux(data, addr(q.data[q.rd * typ.size]), typ, q, mLoad)
  191. q.rd = (q.rd + 1) and q.mask
  192. template lockChannel(q, action): untyped =
  193. acquireSys(q.lock)
  194. action
  195. releaseSys(q.lock)
  196. proc sendImpl(q: PRawChannel, typ: PNimType, msg: pointer, noBlock: bool): bool =
  197. if q.mask == ChannelDeadMask:
  198. sysFatal(DeadThreadError, "cannot send message; thread died")
  199. acquireSys(q.lock)
  200. if q.maxItems > 0:
  201. # Wait until count is less than maxItems
  202. if noBlock and q.count >= q.maxItems:
  203. releaseSys(q.lock)
  204. return
  205. while q.count >= q.maxItems:
  206. waitSysCond(q.cond, q.lock)
  207. rawSend(q, msg, typ)
  208. q.elemType = typ
  209. releaseSys(q.lock)
  210. signalSysCond(q.cond)
  211. result = true
  212. proc send*[TMsg](c: var Channel[TMsg], msg: TMsg) {.inline.} =
  213. ## sends a message to a thread. `msg` is deeply copied.
  214. discard sendImpl(cast[PRawChannel](addr c), cast[PNimType](getTypeInfo(msg)), unsafeAddr(msg), false)
  215. proc trySend*[TMsg](c: var Channel[TMsg], msg: TMsg): bool {.inline.} =
  216. ## Tries to send a message to a thread. `msg` is deeply copied. Doesn't block.
  217. ## Returns `false` if the message was not sent because number of pending items
  218. ## in the channel exceeded `maxItems`.
  219. sendImpl(cast[PRawChannel](addr c), cast[PNimType](getTypeInfo(msg)), unsafeAddr(msg), true)
  220. proc llRecv(q: PRawChannel, res: pointer, typ: PNimType) =
  221. q.ready = true
  222. while q.count <= 0:
  223. waitSysCond(q.cond, q.lock)
  224. q.ready = false
  225. if typ != q.elemType:
  226. releaseSys(q.lock)
  227. sysFatal(ValueError, "cannot receive message of wrong type")
  228. rawRecv(q, res, typ)
  229. if q.maxItems > 0 and q.count == q.maxItems - 1:
  230. # Parent thread is awaiting in send. Wake it up.
  231. signalSysCond(q.cond)
  232. proc recv*[TMsg](c: var Channel[TMsg]): TMsg =
  233. ## receives a message from the channel `c`. This blocks until
  234. ## a message has arrived! You may use ``peek`` to avoid the blocking.
  235. var q = cast[PRawChannel](addr(c))
  236. acquireSys(q.lock)
  237. llRecv(q, addr(result), cast[PNimType](getTypeInfo(result)))
  238. releaseSys(q.lock)
  239. proc tryRecv*[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool,
  240. msg: TMsg] =
  241. ## Tries to receive a message from the channel `c`, but this can fail
  242. ## for all sort of reasons, including contention. If it fails,
  243. ## it returns ``(false, default(msg))`` otherwise it
  244. ## returns ``(true, msg)``.
  245. var q = cast[PRawChannel](addr(c))
  246. if q.mask != ChannelDeadMask:
  247. if tryAcquireSys(q.lock):
  248. if q.count > 0:
  249. llRecv(q, addr(result.msg), cast[PNimType](getTypeInfo(result.msg)))
  250. result.dataAvailable = true
  251. releaseSys(q.lock)
  252. proc peek*[TMsg](c: var Channel[TMsg]): int =
  253. ## returns the current number of messages in the channel `c`. Returns -1
  254. ## if the channel has been closed. **Note**: This is dangerous to use
  255. ## as it encourages races. It's much better to use ``tryRecv`` instead.
  256. var q = cast[PRawChannel](addr(c))
  257. if q.mask != ChannelDeadMask:
  258. lockChannel(q):
  259. result = q.count
  260. else:
  261. result = -1
  262. proc open*[TMsg](c: var Channel[TMsg], maxItems: int = 0) =
  263. ## opens a channel `c` for inter thread communication. The `send` operation
  264. ## will block until number of unprocessed items is less than `maxItems`.
  265. ## For unlimited queue set `maxItems` to 0.
  266. initRawChannel(addr(c), maxItems)
  267. proc close*[TMsg](c: var Channel[TMsg]) =
  268. ## closes a channel `c` and frees its associated resources.
  269. deinitRawChannel(addr(c))
  270. proc ready*[TMsg](c: var Channel[TMsg]): bool =
  271. ## returns true iff some thread is waiting on the channel `c` for
  272. ## new messages.
  273. var q = cast[PRawChannel](addr(c))
  274. result = q.ready