channels.nim 10 KB

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