channels_builtin.nim 15 KB

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