channels.nim 11 KB

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