channels.nim 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. ##
  23. ## Example
  24. ## =======
  25. ## The following is a simple example of two different ways to use channels:
  26. ## blocking and non-blocking.
  27. ##
  28. ## .. code-block :: Nim
  29. ## # Be sure to compile with --threads:on.
  30. ## # The channels and threads modules are part of system and should not be
  31. ## # imported.
  32. ## import os
  33. ##
  34. ## # Channels can either be:
  35. ## # - declared at the module level, or
  36. ## # - passed to procedures by ptr (raw pointer) -- see note on safety.
  37. ## #
  38. ## # For simplicity, in this example a channel is declared at module scope.
  39. ## # Channels are generic, and they include support for passing objects between
  40. ## # threads.
  41. ## # Note that objects passed through channels will be deeply copied.
  42. ## var chan: Channel[string]
  43. ##
  44. ## # This proc will be run in another thread using the threads module.
  45. ## proc firstWorker() =
  46. ## chan.send("Hello World!")
  47. ##
  48. ## # This is another proc to run in a background thread. This proc takes a while
  49. ## # to send the message since it sleeps for 2 seconds (or 2000 milliseconds).
  50. ## proc secondWorker() =
  51. ## sleep(2000)
  52. ## chan.send("Another message")
  53. ##
  54. ## # Initialize the channel.
  55. ## chan.open()
  56. ##
  57. ## # Launch the worker.
  58. ## var worker1: Thread[void]
  59. ## createThread(worker1, firstWorker)
  60. ##
  61. ## # Block until the message arrives, then print it out.
  62. ## echo chan.recv() # "Hello World!"
  63. ##
  64. ## # Wait for the thread to exit before moving on to the next example.
  65. ## worker1.joinThread()
  66. ##
  67. ## # Launch the other worker.
  68. ## var worker2: Thread[void]
  69. ## createThread(worker2, secondWorker)
  70. ## # This time, use a non-blocking approach with tryRecv.
  71. ## # Since the main thread is not blocked, it could be used to perform other
  72. ## # useful work while it waits for data to arrive on the channel.
  73. ## while true:
  74. ## let tried = chan.tryRecv()
  75. ## if tried.dataAvailable:
  76. ## echo tried.msg # "Another message"
  77. ## break
  78. ##
  79. ## echo "Pretend I'm doing useful work..."
  80. ## # For this example, sleep in order not to flood stdout with the above
  81. ## # message.
  82. ## sleep(400)
  83. ##
  84. ## # Wait for the second thread to exit before cleaning up the channel.
  85. ## worker2.joinThread()
  86. ##
  87. ## # Clean up the channel.
  88. ## chan.close()
  89. ##
  90. ## Sample output
  91. ## -------------
  92. ## The program should output something similar to this, but keep in mind that
  93. ## exact results may vary in the real world::
  94. ## Hello World!
  95. ## Pretend I'm doing useful work...
  96. ## Pretend I'm doing useful work...
  97. ## Pretend I'm doing useful work...
  98. ## Pretend I'm doing useful work...
  99. ## Pretend I'm doing useful work...
  100. ## Another message
  101. ##
  102. ## Passing Channels Safely
  103. ## ----------------------
  104. ## Note that when passing objects to procedures on another thread by pointer
  105. ## (for example through a thread's argument), objects created using the default
  106. ## allocator will use thread-local, GC-managed memory. Thus it is generally
  107. ## safer to store channel objects in global variables (as in the above example),
  108. ## in which case they will use a process-wide (thread-safe) shared heap.
  109. ##
  110. ## However, it is possible to manually allocate shared memory for channels
  111. ## using e.g. ``system.allocShared0`` and pass these pointers through thread
  112. ## arguments:
  113. ##
  114. ## .. code-block :: Nim
  115. ## proc worker(channel: ptr Channel[string]) =
  116. ## let greeting = channel[].recv()
  117. ## echo greeting
  118. ##
  119. ## proc localChannelExample() =
  120. ## # Use allocShared0 to allocate some shared-heap memory and zero it.
  121. ## # The usual warnings about dealing with raw pointers apply. Exercise caution.
  122. ## var channel = cast[ptr Channel[string]](
  123. ## allocShared0(sizeof(Channel[string]))
  124. ## )
  125. ## channel[].open()
  126. ## # Create a thread which will receive the channel as an argument.
  127. ## var thread: Thread[ptr Channel[string]]
  128. ## createThread(thread, worker, channel)
  129. ## channel[].send("Hello from the main thread!")
  130. ## # Clean up resources.
  131. ## thread.joinThread()
  132. ## channel[].close()
  133. ## deallocShared(channel)
  134. ##
  135. ## localChannelExample() # "Hello from the main thread!"
  136. when not declared(ThisIsSystem):
  137. {.error: "You must not import this module explicitly".}
  138. type
  139. pbytes = ptr array[0.. 0xffff, byte]
  140. RawChannel {.pure, final.} = object ## msg queue for a thread
  141. rd, wr, count, mask, maxItems: int
  142. data: pbytes
  143. lock: SysLock
  144. cond: SysCond
  145. elemType: PNimType
  146. ready: bool
  147. region: MemRegion
  148. PRawChannel = ptr RawChannel
  149. LoadStoreMode = enum mStore, mLoad
  150. Channel* {.gcsafe.}[TMsg] = RawChannel ## a channel for thread communication
  151. const ChannelDeadMask = -2
  152. proc initRawChannel(p: pointer, maxItems: int) =
  153. var c = cast[PRawChannel](p)
  154. initSysLock(c.lock)
  155. initSysCond(c.cond)
  156. c.mask = -1
  157. c.maxItems = maxItems
  158. proc deinitRawChannel(p: pointer) =
  159. var c = cast[PRawChannel](p)
  160. # we need to grab the lock to be safe against sending threads!
  161. acquireSys(c.lock)
  162. c.mask = ChannelDeadMask
  163. deallocOsPages(c.region)
  164. deinitSys(c.lock)
  165. deinitSysCond(c.cond)
  166. proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel,
  167. mode: LoadStoreMode) {.benign.}
  168. proc storeAux(dest, src: pointer, n: ptr TNimNode, t: PRawChannel,
  169. mode: LoadStoreMode) {.benign.} =
  170. var
  171. d = cast[ByteAddress](dest)
  172. s = cast[ByteAddress](src)
  173. case n.kind
  174. of nkSlot: storeAux(cast[pointer](d +% n.offset),
  175. cast[pointer](s +% n.offset), n.typ, t, mode)
  176. of nkList:
  177. for i in 0..n.len-1: storeAux(dest, src, n.sons[i], t, mode)
  178. of nkCase:
  179. copyMem(cast[pointer](d +% n.offset), cast[pointer](s +% n.offset),
  180. n.typ.size)
  181. var m = selectBranch(src, n)
  182. if m != nil: storeAux(dest, src, m, t, mode)
  183. of nkNone: sysAssert(false, "storeAux")
  184. proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel,
  185. mode: LoadStoreMode) =
  186. template `+!`(p: pointer; x: int): pointer =
  187. cast[pointer](cast[int](p) +% x)
  188. var
  189. d = cast[ByteAddress](dest)
  190. s = cast[ByteAddress](src)
  191. sysAssert(mt != nil, "mt == nil")
  192. case mt.kind
  193. of tyString:
  194. if mode == mStore:
  195. var x = cast[PPointer](dest)
  196. var s2 = cast[PPointer](s)[]
  197. if s2 == nil:
  198. x[] = nil
  199. else:
  200. var ss = cast[NimString](s2)
  201. var ns = cast[NimString](alloc(t.region, ss.len+1 + GenericSeqSize))
  202. copyMem(ns, ss, ss.len+1 + GenericSeqSize)
  203. x[] = ns
  204. else:
  205. var x = cast[PPointer](dest)
  206. var s2 = cast[PPointer](s)[]
  207. if s2 == nil:
  208. unsureAsgnRef(x, s2)
  209. else:
  210. let y = copyDeepString(cast[NimString](s2))
  211. #echo "loaded ", cast[int](y), " ", cast[string](y)
  212. unsureAsgnRef(x, y)
  213. dealloc(t.region, s2)
  214. of tySequence:
  215. var s2 = cast[PPointer](src)[]
  216. var seq = cast[PGenericSeq](s2)
  217. var x = cast[PPointer](dest)
  218. if s2 == nil:
  219. if mode == mStore:
  220. x[] = nil
  221. else:
  222. unsureAsgnRef(x, nil)
  223. else:
  224. sysAssert(dest != nil, "dest == nil")
  225. if mode == mStore:
  226. x[] = alloc0(t.region, seq.len *% mt.base.size +% GenericSeqSize)
  227. else:
  228. unsureAsgnRef(x, newSeq(mt, seq.len))
  229. var dst = cast[ByteAddress](cast[PPointer](dest)[])
  230. var dstseq = cast[PGenericSeq](dst)
  231. dstseq.len = seq.len
  232. dstseq.reserved = seq.len
  233. for i in 0..seq.len-1:
  234. storeAux(
  235. cast[pointer](dst +% i*% mt.base.size +% GenericSeqSize),
  236. cast[pointer](cast[ByteAddress](s2) +% i *% mt.base.size +%
  237. GenericSeqSize),
  238. mt.base, t, mode)
  239. if mode != mStore: dealloc(t.region, s2)
  240. of tyObject:
  241. if mt.base != nil:
  242. storeAux(dest, src, mt.base, t, mode)
  243. else:
  244. # copy type field:
  245. var pint = cast[ptr PNimType](dest)
  246. pint[] = cast[ptr PNimType](src)[]
  247. storeAux(dest, src, mt.node, t, mode)
  248. of tyTuple:
  249. storeAux(dest, src, mt.node, t, mode)
  250. of tyArray, tyArrayConstr:
  251. for i in 0..(mt.size div mt.base.size)-1:
  252. storeAux(cast[pointer](d +% i*% mt.base.size),
  253. cast[pointer](s +% i*% mt.base.size), mt.base, t, mode)
  254. of tyRef:
  255. var s = cast[PPointer](src)[]
  256. var x = cast[PPointer](dest)
  257. if s == nil:
  258. if mode == mStore:
  259. x[] = nil
  260. else:
  261. unsureAsgnRef(x, nil)
  262. else:
  263. #let size = if mt.base.kind == tyObject: cast[ptr PNimType](s)[].size
  264. # else: mt.base.size
  265. if mode == mStore:
  266. let dyntype = when declared(usrToCell): usrToCell(s).typ
  267. else: mt
  268. let size = dyntype.base.size
  269. # we store the real dynamic 'ref type' at offset 0, so that
  270. # no information is lost
  271. let a = alloc0(t.region, size+sizeof(pointer))
  272. x[] = a
  273. cast[PPointer](a)[] = dyntype
  274. storeAux(a +! sizeof(pointer), s, dyntype.base, t, mode)
  275. else:
  276. let dyntype = cast[ptr PNimType](s)[]
  277. var obj = newObj(dyntype, dyntype.base.size)
  278. unsureAsgnRef(x, obj)
  279. storeAux(x[], s +! sizeof(pointer), dyntype.base, t, mode)
  280. dealloc(t.region, s)
  281. else:
  282. copyMem(dest, src, mt.size) # copy raw bits
  283. proc rawSend(q: PRawChannel, data: pointer, typ: PNimType) =
  284. ## Adds an `item` to the end of the queue `q`.
  285. var cap = q.mask+1
  286. if q.count >= cap:
  287. # start with capacity for 2 entries in the queue:
  288. if cap == 0: cap = 1
  289. var n = cast[pbytes](alloc0(q.region, cap*2*typ.size))
  290. var z = 0
  291. var i = q.rd
  292. var c = q.count
  293. while c > 0:
  294. dec c
  295. copyMem(addr(n[z*typ.size]), addr(q.data[i*typ.size]), typ.size)
  296. i = (i + 1) and q.mask
  297. inc z
  298. if q.data != nil: dealloc(q.region, q.data)
  299. q.data = n
  300. q.mask = cap*2 - 1
  301. q.wr = q.count
  302. q.rd = 0
  303. storeAux(addr(q.data[q.wr * typ.size]), data, typ, q, mStore)
  304. inc q.count
  305. q.wr = (q.wr + 1) and q.mask
  306. proc rawRecv(q: PRawChannel, data: pointer, typ: PNimType) =
  307. sysAssert q.count > 0, "rawRecv"
  308. dec q.count
  309. storeAux(data, addr(q.data[q.rd * typ.size]), typ, q, mLoad)
  310. q.rd = (q.rd + 1) and q.mask
  311. template lockChannel(q, action): untyped =
  312. acquireSys(q.lock)
  313. action
  314. releaseSys(q.lock)
  315. proc sendImpl(q: PRawChannel, typ: PNimType, msg: pointer, noBlock: bool): bool =
  316. if q.mask == ChannelDeadMask:
  317. sysFatal(DeadThreadError, "cannot send message; thread died")
  318. acquireSys(q.lock)
  319. if q.maxItems > 0:
  320. # Wait until count is less than maxItems
  321. if noBlock and q.count >= q.maxItems:
  322. releaseSys(q.lock)
  323. return
  324. while q.count >= q.maxItems:
  325. waitSysCond(q.cond, q.lock)
  326. rawSend(q, msg, typ)
  327. q.elemType = typ
  328. releaseSys(q.lock)
  329. signalSysCond(q.cond)
  330. result = true
  331. proc send*[TMsg](c: var Channel[TMsg], msg: TMsg) {.inline.} =
  332. ## Sends a message to a thread. `msg` is deeply copied.
  333. discard sendImpl(cast[PRawChannel](addr c), cast[PNimType](getTypeInfo(msg)), unsafeAddr(msg), false)
  334. proc trySend*[TMsg](c: var Channel[TMsg], msg: TMsg): bool {.inline.} =
  335. ## Tries to send a message to a thread.
  336. ##
  337. ## `msg` is deeply copied. Doesn't block.
  338. ##
  339. ## Returns `false` if the message was not sent because number of pending items
  340. ## in the channel exceeded `maxItems`.
  341. sendImpl(cast[PRawChannel](addr c), cast[PNimType](getTypeInfo(msg)), unsafeAddr(msg), true)
  342. proc llRecv(q: PRawChannel, res: pointer, typ: PNimType) =
  343. q.ready = true
  344. while q.count <= 0:
  345. waitSysCond(q.cond, q.lock)
  346. q.ready = false
  347. if typ != q.elemType:
  348. releaseSys(q.lock)
  349. sysFatal(ValueError, "cannot receive message of wrong type")
  350. rawRecv(q, res, typ)
  351. if q.maxItems > 0 and q.count == q.maxItems - 1:
  352. # Parent thread is awaiting in send. Wake it up.
  353. signalSysCond(q.cond)
  354. proc recv*[TMsg](c: var Channel[TMsg]): TMsg =
  355. ## Receives a message from the channel `c`.
  356. ##
  357. ## This blocks until a message has arrived!
  358. ## You may use `peek proc <#peek,Channel[TMsg]>`_ to avoid the blocking.
  359. var q = cast[PRawChannel](addr(c))
  360. acquireSys(q.lock)
  361. llRecv(q, addr(result), cast[PNimType](getTypeInfo(result)))
  362. releaseSys(q.lock)
  363. proc tryRecv*[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool,
  364. msg: TMsg] =
  365. ## Tries to receive a message from the channel `c`, but this can fail
  366. ## for all sort of reasons, including contention.
  367. ##
  368. ## If it fails, it returns ``(false, default(msg))`` otherwise it
  369. ## returns ``(true, msg)``.
  370. var q = cast[PRawChannel](addr(c))
  371. if q.mask != ChannelDeadMask:
  372. if tryAcquireSys(q.lock):
  373. if q.count > 0:
  374. llRecv(q, addr(result.msg), cast[PNimType](getTypeInfo(result.msg)))
  375. result.dataAvailable = true
  376. releaseSys(q.lock)
  377. proc peek*[TMsg](c: var Channel[TMsg]): int =
  378. ## Returns the current number of messages in the channel `c`.
  379. ##
  380. ## Returns -1 if the channel has been closed.
  381. ##
  382. ## **Note**: This is dangerous to use as it encourages races.
  383. ## It's much better to use `tryRecv proc <#tryRecv,Channel[TMsg]>`_ instead.
  384. var q = cast[PRawChannel](addr(c))
  385. if q.mask != ChannelDeadMask:
  386. lockChannel(q):
  387. result = q.count
  388. else:
  389. result = -1
  390. proc open*[TMsg](c: var Channel[TMsg], maxItems: int = 0) =
  391. ## Opens a channel `c` for inter thread communication.
  392. ##
  393. ## The `send` operation will block until number of unprocessed items is
  394. ## less than `maxItems`.
  395. ##
  396. ## For unlimited queue set `maxItems` to 0.
  397. initRawChannel(addr(c), maxItems)
  398. proc close*[TMsg](c: var Channel[TMsg]) =
  399. ## Closes a channel `c` and frees its associated resources.
  400. deinitRawChannel(addr(c))
  401. proc ready*[TMsg](c: var Channel[TMsg]): bool =
  402. ## Returns true iff some thread is waiting on the channel `c` for
  403. ## new messages.
  404. var q = cast[PRawChannel](addr(c))
  405. result = q.ready