channels_builtin.nim 15 KB

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