channels.nim 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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 UncheckedArray[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. when not usesDestructors:
  148. region: MemRegion
  149. PRawChannel = ptr RawChannel
  150. LoadStoreMode = enum mStore, mLoad
  151. Channel* {.gcsafe.}[TMsg] = RawChannel ## a channel for thread communication
  152. const ChannelDeadMask = -2
  153. proc initRawChannel(p: pointer, maxItems: int) =
  154. var c = cast[PRawChannel](p)
  155. initSysLock(c.lock)
  156. initSysCond(c.cond)
  157. c.mask = -1
  158. c.maxItems = maxItems
  159. proc deinitRawChannel(p: pointer) =
  160. var c = cast[PRawChannel](p)
  161. # we need to grab the lock to be safe against sending threads!
  162. acquireSys(c.lock)
  163. c.mask = ChannelDeadMask
  164. when not usesDestructors:
  165. deallocOsPages(c.region)
  166. else:
  167. if c.data != nil: deallocShared(c.data)
  168. deinitSys(c.lock)
  169. deinitSysCond(c.cond)
  170. when not usesDestructors:
  171. proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel,
  172. mode: LoadStoreMode) {.benign.}
  173. proc storeAux(dest, src: pointer, n: ptr TNimNode, t: PRawChannel,
  174. mode: LoadStoreMode) {.benign.} =
  175. var
  176. d = cast[ByteAddress](dest)
  177. s = cast[ByteAddress](src)
  178. case n.kind
  179. of nkSlot: storeAux(cast[pointer](d +% n.offset),
  180. cast[pointer](s +% n.offset), n.typ, t, mode)
  181. of nkList:
  182. for i in 0..n.len-1: storeAux(dest, src, n.sons[i], t, mode)
  183. of nkCase:
  184. copyMem(cast[pointer](d +% n.offset), cast[pointer](s +% n.offset),
  185. n.typ.size)
  186. var m = selectBranch(src, n)
  187. if m != nil: storeAux(dest, src, m, t, mode)
  188. of nkNone: sysAssert(false, "storeAux")
  189. proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel,
  190. mode: LoadStoreMode) =
  191. template `+!`(p: pointer; x: int): pointer =
  192. cast[pointer](cast[int](p) +% x)
  193. var
  194. d = cast[ByteAddress](dest)
  195. s = cast[ByteAddress](src)
  196. sysAssert(mt != nil, "mt == nil")
  197. case mt.kind
  198. of tyString:
  199. if mode == mStore:
  200. var x = cast[PPointer](dest)
  201. var s2 = cast[PPointer](s)[]
  202. if s2 == nil:
  203. x[] = nil
  204. else:
  205. var ss = cast[NimString](s2)
  206. var ns = cast[NimString](alloc(t.region, GenericSeqSize + ss.len+1))
  207. copyMem(ns, ss, ss.len+1 + GenericSeqSize)
  208. x[] = ns
  209. else:
  210. var x = cast[PPointer](dest)
  211. var s2 = cast[PPointer](s)[]
  212. if s2 == nil:
  213. unsureAsgnRef(x, s2)
  214. else:
  215. let y = copyDeepString(cast[NimString](s2))
  216. #echo "loaded ", cast[int](y), " ", cast[string](y)
  217. unsureAsgnRef(x, y)
  218. dealloc(t.region, s2)
  219. of tySequence:
  220. var s2 = cast[PPointer](src)[]
  221. var seq = cast[PGenericSeq](s2)
  222. var x = cast[PPointer](dest)
  223. if s2 == nil:
  224. if mode == mStore:
  225. x[] = nil
  226. else:
  227. unsureAsgnRef(x, nil)
  228. else:
  229. sysAssert(dest != nil, "dest == nil")
  230. if mode == mStore:
  231. x[] = alloc0(t.region, align(GenericSeqSize, mt.base.align) +% seq.len *% mt.base.size)
  232. else:
  233. unsureAsgnRef(x, newSeq(mt, seq.len))
  234. var dst = cast[ByteAddress](cast[PPointer](dest)[])
  235. var dstseq = cast[PGenericSeq](dst)
  236. dstseq.len = seq.len
  237. dstseq.reserved = seq.len
  238. for i in 0..seq.len-1:
  239. storeAux(
  240. cast[pointer](dst +% align(GenericSeqSize, mt.base.align) +% i*% mt.base.size),
  241. cast[pointer](cast[ByteAddress](s2) +% align(GenericSeqSize, mt.base.align) +%
  242. i *% mt.base.size),
  243. mt.base, t, mode)
  244. if mode != mStore: dealloc(t.region, s2)
  245. of tyObject:
  246. if mt.base != nil:
  247. storeAux(dest, src, mt.base, t, mode)
  248. else:
  249. # copy type field:
  250. var pint = cast[ptr PNimType](dest)
  251. pint[] = cast[ptr PNimType](src)[]
  252. storeAux(dest, src, mt.node, t, mode)
  253. of tyTuple:
  254. storeAux(dest, src, mt.node, t, mode)
  255. of tyArray, tyArrayConstr:
  256. for i in 0..(mt.size div mt.base.size)-1:
  257. storeAux(cast[pointer](d +% i*% mt.base.size),
  258. cast[pointer](s +% i*% mt.base.size), mt.base, t, mode)
  259. of tyRef:
  260. var s = cast[PPointer](src)[]
  261. var x = cast[PPointer](dest)
  262. if s == nil:
  263. if mode == mStore:
  264. x[] = nil
  265. else:
  266. unsureAsgnRef(x, nil)
  267. else:
  268. #let size = if mt.base.kind == tyObject: cast[ptr PNimType](s)[].size
  269. # else: mt.base.size
  270. if mode == mStore:
  271. let dyntype = when declared(usrToCell): usrToCell(s).typ
  272. else: mt
  273. let size = dyntype.base.size
  274. # we store the real dynamic 'ref type' at offset 0, so that
  275. # no information is lost
  276. let a = alloc0(t.region, size+sizeof(pointer))
  277. x[] = a
  278. cast[PPointer](a)[] = dyntype
  279. storeAux(a +! sizeof(pointer), s, dyntype.base, t, mode)
  280. else:
  281. let dyntype = cast[ptr PNimType](s)[]
  282. var obj = newObj(dyntype, dyntype.base.size)
  283. unsureAsgnRef(x, obj)
  284. storeAux(x[], s +! sizeof(pointer), dyntype.base, t, mode)
  285. dealloc(t.region, s)
  286. else:
  287. copyMem(dest, src, mt.size) # copy raw bits
  288. proc rawSend(q: PRawChannel, data: pointer, typ: PNimType) =
  289. ## Adds an `item` to the end of the queue `q`.
  290. var cap = q.mask+1
  291. if q.count >= cap:
  292. # start with capacity for 2 entries in the queue:
  293. if cap == 0: cap = 1
  294. when not usesDestructors:
  295. var n = cast[pbytes](alloc0(q.region, cap*2*typ.size))
  296. else:
  297. var n = cast[pbytes](allocShared0(cap*2*typ.size))
  298. var z = 0
  299. var i = q.rd
  300. var c = q.count
  301. while c > 0:
  302. dec c
  303. copyMem(addr(n[z*typ.size]), addr(q.data[i*typ.size]), typ.size)
  304. i = (i + 1) and q.mask
  305. inc z
  306. if q.data != nil:
  307. when not usesDestructors:
  308. dealloc(q.region, q.data)
  309. else:
  310. deallocShared(q.data)
  311. q.data = n
  312. q.mask = cap*2 - 1
  313. q.wr = q.count
  314. q.rd = 0
  315. when not usesDestructors:
  316. storeAux(addr(q.data[q.wr * typ.size]), data, typ, q, mStore)
  317. else:
  318. copyMem(addr(q.data[q.wr * typ.size]), data, typ.size)
  319. inc q.count
  320. q.wr = (q.wr + 1) and q.mask
  321. proc rawRecv(q: PRawChannel, data: pointer, typ: PNimType) =
  322. sysAssert q.count > 0, "rawRecv"
  323. dec q.count
  324. when not usesDestructors:
  325. storeAux(data, addr(q.data[q.rd * typ.size]), typ, q, mLoad)
  326. else:
  327. copyMem(data, addr(q.data[q.rd * typ.size]), typ.size)
  328. q.rd = (q.rd + 1) and q.mask
  329. template lockChannel(q, action): untyped =
  330. acquireSys(q.lock)
  331. action
  332. releaseSys(q.lock)
  333. proc sendImpl(q: PRawChannel, typ: PNimType, msg: pointer, noBlock: bool): bool =
  334. if q.mask == ChannelDeadMask:
  335. sysFatal(DeadThreadDefect, "cannot send message; thread died")
  336. acquireSys(q.lock)
  337. if q.maxItems > 0:
  338. # Wait until count is less than maxItems
  339. if noBlock and q.count >= q.maxItems:
  340. releaseSys(q.lock)
  341. return
  342. while q.count >= q.maxItems:
  343. waitSysCond(q.cond, q.lock)
  344. rawSend(q, msg, typ)
  345. q.elemType = typ
  346. releaseSys(q.lock)
  347. signalSysCond(q.cond)
  348. result = true
  349. proc send*[TMsg](c: var Channel[TMsg], msg: sink TMsg) {.inline.} =
  350. ## Sends a message to a thread. `msg` is deeply copied.
  351. discard sendImpl(cast[PRawChannel](addr c), cast[PNimType](getTypeInfo(msg)), unsafeAddr(msg), false)
  352. when defined(gcDestructors):
  353. wasMoved(msg)
  354. proc trySend*[TMsg](c: var Channel[TMsg], msg: sink TMsg): bool {.inline.} =
  355. ## Tries to send a message to a thread.
  356. ##
  357. ## `msg` is deeply copied. Doesn't block.
  358. ##
  359. ## Returns `false` if the message was not sent because number of pending items
  360. ## in the channel exceeded `maxItems`.
  361. result = sendImpl(cast[PRawChannel](addr c), cast[PNimType](getTypeInfo(msg)), unsafeAddr(msg), true)
  362. when defined(gcDestructors):
  363. if result:
  364. wasMoved(msg)
  365. proc llRecv(q: PRawChannel, res: pointer, typ: PNimType) =
  366. q.ready = true
  367. while q.count <= 0:
  368. waitSysCond(q.cond, q.lock)
  369. q.ready = false
  370. if typ != q.elemType:
  371. releaseSys(q.lock)
  372. sysFatal(ValueError, "cannot receive message of wrong type")
  373. rawRecv(q, res, typ)
  374. if q.maxItems > 0 and q.count == q.maxItems - 1:
  375. # Parent thread is awaiting in send. Wake it up.
  376. signalSysCond(q.cond)
  377. proc recv*[TMsg](c: var Channel[TMsg]): TMsg =
  378. ## Receives a message from the channel `c`.
  379. ##
  380. ## This blocks until a message has arrived!
  381. ## You may use `peek proc <#peek,Channel[TMsg]>`_ to avoid the blocking.
  382. var q = cast[PRawChannel](addr(c))
  383. acquireSys(q.lock)
  384. llRecv(q, addr(result), cast[PNimType](getTypeInfo(result)))
  385. releaseSys(q.lock)
  386. proc tryRecv*[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool,
  387. msg: TMsg] =
  388. ## Tries to receive a message from the channel `c`, but this can fail
  389. ## for all sort of reasons, including contention.
  390. ##
  391. ## If it fails, it returns ``(false, default(msg))`` otherwise it
  392. ## returns ``(true, msg)``.
  393. var q = cast[PRawChannel](addr(c))
  394. if q.mask != ChannelDeadMask:
  395. if tryAcquireSys(q.lock):
  396. if q.count > 0:
  397. llRecv(q, addr(result.msg), cast[PNimType](getTypeInfo(result.msg)))
  398. result.dataAvailable = true
  399. releaseSys(q.lock)
  400. proc peek*[TMsg](c: var Channel[TMsg]): int =
  401. ## Returns the current number of messages in the channel `c`.
  402. ##
  403. ## Returns -1 if the channel has been closed.
  404. ##
  405. ## **Note**: This is dangerous to use as it encourages races.
  406. ## It's much better to use `tryRecv proc <#tryRecv,Channel[TMsg]>`_ instead.
  407. var q = cast[PRawChannel](addr(c))
  408. if q.mask != ChannelDeadMask:
  409. lockChannel(q):
  410. result = q.count
  411. else:
  412. result = -1
  413. proc open*[TMsg](c: var Channel[TMsg], maxItems: int = 0) =
  414. ## Opens a channel `c` for inter thread communication.
  415. ##
  416. ## The `send` operation will block until number of unprocessed items is
  417. ## less than `maxItems`.
  418. ##
  419. ## For unlimited queue set `maxItems` to 0.
  420. initRawChannel(addr(c), maxItems)
  421. proc close*[TMsg](c: var Channel[TMsg]) =
  422. ## Closes a channel `c` and frees its associated resources.
  423. deinitRawChannel(addr(c))
  424. proc ready*[TMsg](c: var Channel[TMsg]): bool =
  425. ## Returns true if some thread is waiting on the channel `c` for
  426. ## new messages.
  427. var q = cast[PRawChannel](addr(c))
  428. result = q.ready