threads.nim 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Thread support for Nim.
  10. ##
  11. ## **Note**: This is part of the system module. Do not import it directly.
  12. ## To activate thread support you need to compile
  13. ## with the ``--threads:on`` command line switch.
  14. ##
  15. ## Nim's memory model for threads is quite different from other common
  16. ## programming languages (C, Pascal): Each thread has its own
  17. ## (garbage collected) heap and sharing of memory is restricted. This helps
  18. ## to prevent race conditions and improves efficiency. See `the manual for
  19. ## details of this memory model <manual.html#threads>`_.
  20. ##
  21. ## Examples
  22. ## ========
  23. ##
  24. ## .. code-block:: Nim
  25. ##
  26. ## import locks
  27. ##
  28. ## var
  29. ## thr: array[0..4, Thread[tuple[a,b: int]]]
  30. ## L: Lock
  31. ##
  32. ## proc threadFunc(interval: tuple[a,b: int]) {.thread.} =
  33. ## for i in interval.a..interval.b:
  34. ## acquire(L) # lock stdout
  35. ## echo i
  36. ## release(L)
  37. ##
  38. ## initLock(L)
  39. ##
  40. ## for i in 0..high(thr):
  41. ## createThread(thr[i], threadFunc, (i*10, i*10+5))
  42. ## joinThreads(thr)
  43. when not declared(ThisIsSystem):
  44. {.error: "You must not import this module explicitly".}
  45. const
  46. StackGuardSize = 4096
  47. ThreadStackMask =
  48. when defined(genode):
  49. 1024*64*sizeof(int)-1
  50. else:
  51. 1024*256*sizeof(int)-1
  52. ThreadStackSize = ThreadStackMask+1 - StackGuardSize
  53. #const globalsSlot = ThreadVarSlot(0)
  54. #sysAssert checkSlot.int == globalsSlot.int
  55. # create for the main thread. Note: do not insert this data into the list
  56. # of all threads; it's not to be stopped etc.
  57. when not defined(useNimRtl):
  58. #when not defined(createNimRtl): initStackBottom()
  59. when declared(initGC):
  60. initGC()
  61. when not emulatedThreadVars:
  62. type ThreadType {.pure.} = enum
  63. None = 0,
  64. NimThread = 1,
  65. ForeignThread = 2
  66. var
  67. threadType {.rtlThreadVar.}: ThreadType
  68. threadType = ThreadType.NimThread
  69. # We jump through some hops here to ensure that Nim thread procs can have
  70. # the Nim calling convention. This is needed because thread procs are
  71. # ``stdcall`` on Windows and ``noconv`` on UNIX. Alternative would be to just
  72. # use ``stdcall`` since it is mapped to ``noconv`` on UNIX anyway.
  73. type
  74. Thread*[TArg] = object
  75. core: PGcThread
  76. sys: SysThread
  77. when TArg is void:
  78. dataFn: proc () {.nimcall, gcsafe.}
  79. else:
  80. dataFn: proc (m: TArg) {.nimcall, gcsafe.}
  81. data: TArg
  82. var
  83. threadDestructionHandlers {.rtlThreadVar.}: seq[proc () {.closure, gcsafe.}]
  84. proc onThreadDestruction*(handler: proc () {.closure, gcsafe.}) =
  85. ## Registers a *thread local* handler that is called at the thread's
  86. ## destruction.
  87. ##
  88. ## A thread is destructed when the ``.thread`` proc returns
  89. ## normally or when it raises an exception. Note that unhandled exceptions
  90. ## in a thread nevertheless cause the whole process to die.
  91. threadDestructionHandlers.add handler
  92. template afterThreadRuns() =
  93. for i in countdown(threadDestructionHandlers.len-1, 0):
  94. threadDestructionHandlers[i]()
  95. when not defined(boehmgc) and not hasSharedHeap and not defined(gogc) and not defined(gcRegions):
  96. proc deallocOsPages() {.rtl.}
  97. when defined(boehmgc):
  98. type GCStackBaseProc = proc(sb: pointer, t: pointer) {.noconv.}
  99. proc boehmGC_call_with_stack_base(sbp: GCStackBaseProc, p: pointer)
  100. {.importc: "GC_call_with_stack_base", boehmGC.}
  101. proc boehmGC_register_my_thread(sb: pointer)
  102. {.importc: "GC_register_my_thread", boehmGC.}
  103. proc boehmGC_unregister_my_thread()
  104. {.importc: "GC_unregister_my_thread", boehmGC.}
  105. proc threadProcWrapDispatch[TArg](sb: pointer, thrd: pointer) {.noconv.} =
  106. boehmGC_register_my_thread(sb)
  107. try:
  108. let thrd = cast[ptr Thread[TArg]](thrd)
  109. when TArg is void:
  110. thrd.dataFn()
  111. else:
  112. thrd.dataFn(thrd.data)
  113. finally:
  114. afterThreadRuns()
  115. boehmGC_unregister_my_thread()
  116. else:
  117. proc threadProcWrapDispatch[TArg](thrd: ptr Thread[TArg]) =
  118. try:
  119. when TArg is void:
  120. thrd.dataFn()
  121. else:
  122. when defined(nimV2):
  123. thrd.dataFn(thrd.data)
  124. else:
  125. var x: TArg
  126. deepCopy(x, thrd.data)
  127. thrd.dataFn(x)
  128. finally:
  129. afterThreadRuns()
  130. proc threadProcWrapStackFrame[TArg](thrd: ptr Thread[TArg]) =
  131. when defined(boehmgc):
  132. boehmGC_call_with_stack_base(threadProcWrapDispatch[TArg], thrd)
  133. elif not defined(nogc) and not defined(gogc) and not defined(gcRegions) and not usesDestructors:
  134. var p {.volatile.}: proc(a: ptr Thread[TArg]) {.nimcall, gcsafe.} =
  135. threadProcWrapDispatch[TArg]
  136. # init the GC for refc/markandsweep
  137. nimGC_setStackBottom(addr(p))
  138. initGC()
  139. when declared(threadType):
  140. threadType = ThreadType.NimThread
  141. p(thrd)
  142. when declared(deallocOsPages): deallocOsPages()
  143. else:
  144. threadProcWrapDispatch(thrd)
  145. template threadProcWrapperBody(closure: untyped): untyped =
  146. var thrd = cast[ptr Thread[TArg]](closure)
  147. var core = thrd.core
  148. when declared(globalsSlot): threadVarSetValue(globalsSlot, thrd.core)
  149. threadProcWrapStackFrame(thrd)
  150. # Since an unhandled exception terminates the whole process (!), there is
  151. # no need for a ``try finally`` here, nor would it be correct: The current
  152. # exception is tried to be re-raised by the code-gen after the ``finally``!
  153. # However this is doomed to fail, because we already unmapped every heap
  154. # page!
  155. # mark as not running anymore:
  156. thrd.core = nil
  157. thrd.dataFn = nil
  158. deallocShared(cast[pointer](core))
  159. {.push stack_trace:off.}
  160. when defined(windows):
  161. proc threadProcWrapper[TArg](closure: pointer): int32 {.stdcall.} =
  162. threadProcWrapperBody(closure)
  163. # implicitly return 0
  164. elif defined(genode):
  165. proc threadProcWrapper[TArg](closure: pointer) {.noconv.} =
  166. threadProcWrapperBody(closure)
  167. else:
  168. proc threadProcWrapper[TArg](closure: pointer): pointer {.noconv.} =
  169. threadProcWrapperBody(closure)
  170. {.pop.}
  171. proc running*[TArg](t: Thread[TArg]): bool {.inline.} =
  172. ## Returns true if `t` is running.
  173. result = t.dataFn != nil
  174. proc handle*[TArg](t: Thread[TArg]): SysThread {.inline.} =
  175. ## Returns the thread handle of `t`.
  176. result = t.sys
  177. when hostOS == "windows":
  178. const MAXIMUM_WAIT_OBJECTS = 64
  179. proc joinThread*[TArg](t: Thread[TArg]) {.inline.} =
  180. ## Waits for the thread `t` to finish.
  181. discard waitForSingleObject(t.sys, -1'i32)
  182. proc joinThreads*[TArg](t: varargs[Thread[TArg]]) =
  183. ## Waits for every thread in `t` to finish.
  184. var a: array[MAXIMUM_WAIT_OBJECTS, SysThread]
  185. var k = 0
  186. while k < len(t):
  187. var count = min(len(t) - k, MAXIMUM_WAIT_OBJECTS)
  188. for i in 0..(count - 1): a[i] = t[i + k].sys
  189. discard waitForMultipleObjects(int32(count),
  190. cast[ptr SysThread](addr(a)), 1, -1)
  191. inc(k, MAXIMUM_WAIT_OBJECTS)
  192. elif defined(genode):
  193. proc joinThread*[TArg](t: Thread[TArg]) {.importcpp.}
  194. ## Waits for the thread `t` to finish.
  195. proc joinThreads*[TArg](t: varargs[Thread[TArg]]) =
  196. ## Waits for every thread in `t` to finish.
  197. for i in 0..t.high: joinThread(t[i])
  198. else:
  199. proc joinThread*[TArg](t: Thread[TArg]) {.inline.} =
  200. ## Waits for the thread `t` to finish.
  201. discard pthread_join(t.sys, nil)
  202. proc joinThreads*[TArg](t: varargs[Thread[TArg]]) =
  203. ## Waits for every thread in `t` to finish.
  204. for i in 0..t.high: joinThread(t[i])
  205. when false:
  206. # XXX a thread should really release its heap here somehow:
  207. proc destroyThread*[TArg](t: var Thread[TArg]) =
  208. ## Forces the thread `t` to terminate. This is potentially dangerous if
  209. ## you don't have full control over `t` and its acquired resources.
  210. when hostOS == "windows":
  211. discard TerminateThread(t.sys, 1'i32)
  212. else:
  213. discard pthread_cancel(t.sys)
  214. when declared(registerThread): unregisterThread(addr(t))
  215. t.dataFn = nil
  216. ## if thread `t` already exited, `t.core` will be `null`.
  217. if not isNil(t.core):
  218. deallocShared(t.core)
  219. t.core = nil
  220. when hostOS == "windows":
  221. proc createThread*[TArg](t: var Thread[TArg],
  222. tp: proc (arg: TArg) {.thread, nimcall.},
  223. param: TArg) =
  224. ## Creates a new thread `t` and starts its execution.
  225. ##
  226. ## Entry point is the proc `tp`.
  227. ## `param` is passed to `tp`. `TArg` can be ``void`` if you
  228. ## don't need to pass any data to the thread.
  229. t.core = cast[PGcThread](allocShared0(sizeof(GcThread)))
  230. when TArg isnot void: t.data = param
  231. t.dataFn = tp
  232. when hasSharedHeap: t.core.stackSize = ThreadStackSize
  233. var dummyThreadId: int32
  234. t.sys = createThread(nil, ThreadStackSize, threadProcWrapper[TArg],
  235. addr(t), 0'i32, dummyThreadId)
  236. if t.sys <= 0:
  237. raise newException(ResourceExhaustedError, "cannot create thread")
  238. proc pinToCpu*[Arg](t: var Thread[Arg]; cpu: Natural) =
  239. ## Pins a thread to a `CPU`:idx:.
  240. ##
  241. ## In other words sets a thread's `affinity`:idx:.
  242. ## If you don't know what this means, you shouldn't use this proc.
  243. setThreadAffinityMask(t.sys, uint(1 shl cpu))
  244. elif defined(genode):
  245. var affinityOffset: cuint = 1
  246. ## CPU affinity offset for next thread, safe to roll-over.
  247. proc createThread*[TArg](t: var Thread[TArg],
  248. tp: proc (arg: TArg) {.thread, nimcall.},
  249. param: TArg) =
  250. t.core = cast[PGcThread](allocShared0(sizeof(GcThread)))
  251. when TArg isnot void: t.data = param
  252. t.dataFn = tp
  253. when hasSharedHeap: t.stackSize = ThreadStackSize
  254. t.sys.initThread(
  255. runtimeEnv,
  256. ThreadStackSize.culonglong,
  257. threadProcWrapper[TArg], addr(t), affinityOffset)
  258. inc affinityOffset
  259. proc pinToCpu*[Arg](t: var Thread[Arg]; cpu: Natural) =
  260. {.hint: "cannot change Genode thread CPU affinity after initialization".}
  261. discard
  262. else:
  263. proc createThread*[TArg](t: var Thread[TArg],
  264. tp: proc (arg: TArg) {.thread, nimcall.},
  265. param: TArg) =
  266. ## Creates a new thread `t` and starts its execution.
  267. ##
  268. ## Entry point is the proc `tp`. `param` is passed to `tp`.
  269. ## `TArg` can be ``void`` if you
  270. ## don't need to pass any data to the thread.
  271. t.core = cast[PGcThread](allocShared0(sizeof(GcThread)))
  272. when TArg isnot void: t.data = param
  273. t.dataFn = tp
  274. when hasSharedHeap: t.core.stackSize = ThreadStackSize
  275. var a {.noinit.}: Pthread_attr
  276. doAssert pthread_attr_init(a) == 0
  277. let setstacksizeResult = pthread_attr_setstacksize(a, ThreadStackSize)
  278. when not defined(ios):
  279. # This fails on iOS
  280. doAssert(setstacksizeResult == 0)
  281. if pthread_create(t.sys, a, threadProcWrapper[TArg], addr(t)) != 0:
  282. raise newException(ResourceExhaustedError, "cannot create thread")
  283. doAssert pthread_attr_destroy(a) == 0
  284. proc pinToCpu*[Arg](t: var Thread[Arg]; cpu: Natural) =
  285. ## Pins a thread to a `CPU`:idx:.
  286. ##
  287. ## In other words sets a thread's `affinity`:idx:.
  288. ## If you don't know what this means, you shouldn't use this proc.
  289. when not defined(macosx):
  290. var s {.noinit.}: CpuSet
  291. cpusetZero(s)
  292. cpusetIncl(cpu.cint, s)
  293. setAffinity(t.sys, csize_t(sizeof(s)), s)
  294. proc createThread*(t: var Thread[void], tp: proc () {.thread, nimcall.}) =
  295. createThread[void](t, tp)
  296. # we need to cache current threadId to not perform syscall all the time
  297. var threadId {.threadvar.}: int
  298. when defined(windows):
  299. proc getThreadId*(): int =
  300. ## Gets the ID of the currently running thread.
  301. if threadId == 0:
  302. threadId = int(getCurrentThreadId())
  303. result = threadId
  304. elif defined(linux):
  305. proc syscall(arg: clong): clong {.varargs, importc: "syscall", header: "<unistd.h>".}
  306. when defined(amd64):
  307. const NR_gettid = clong(186)
  308. else:
  309. var NR_gettid {.importc: "__NR_gettid", header: "<sys/syscall.h>".}: clong
  310. proc getThreadId*(): int =
  311. ## Gets the ID of the currently running thread.
  312. if threadId == 0:
  313. threadId = int(syscall(NR_gettid))
  314. result = threadId
  315. elif defined(dragonfly):
  316. proc lwp_gettid(): int32 {.importc, header: "unistd.h".}
  317. proc getThreadId*(): int =
  318. ## Gets the ID of the currently running thread.
  319. if threadId == 0:
  320. threadId = int(lwp_gettid())
  321. result = threadId
  322. elif defined(openbsd):
  323. proc getthrid(): int32 {.importc: "getthrid", header: "<unistd.h>".}
  324. proc getThreadId*(): int =
  325. ## get the ID of the currently running thread.
  326. if threadId == 0:
  327. threadId = int(getthrid())
  328. result = threadId
  329. elif defined(netbsd):
  330. proc lwp_self(): int32 {.importc: "_lwp_self", header: "<lwp.h>".}
  331. proc getThreadId*(): int =
  332. ## Gets the ID of the currently running thread.
  333. if threadId == 0:
  334. threadId = int(lwp_self())
  335. result = threadId
  336. elif defined(freebsd):
  337. proc syscall(arg: cint, arg0: ptr cint): cint {.varargs, importc: "syscall", header: "<unistd.h>".}
  338. var SYS_thr_self {.importc:"SYS_thr_self", header:"<sys/syscall.h>"}: cint
  339. proc getThreadId*(): int =
  340. ## Gets the ID of the currently running thread.
  341. var tid = 0.cint
  342. if threadId == 0:
  343. discard syscall(SYS_thr_self, addr tid)
  344. threadId = tid
  345. result = threadId
  346. elif defined(macosx):
  347. proc syscall(arg: cint): cint {.varargs, importc: "syscall", header: "<unistd.h>".}
  348. var SYS_thread_selfid {.importc:"SYS_thread_selfid", header:"<sys/syscall.h>".}: cint
  349. proc getThreadId*(): int =
  350. ## Gets the ID of the currently running thread.
  351. if threadId == 0:
  352. threadId = int(syscall(SYS_thread_selfid))
  353. result = threadId
  354. elif defined(solaris):
  355. type thread_t {.importc: "thread_t", header: "<thread.h>".} = distinct int
  356. proc thr_self(): thread_t {.importc, header: "<thread.h>".}
  357. proc getThreadId*(): int =
  358. ## Gets the ID of the currently running thread.
  359. if threadId == 0:
  360. threadId = int(thr_self())
  361. result = threadId
  362. elif defined(haiku):
  363. type thr_id {.importc: "thread_id", header: "<OS.h>".} = distinct int32
  364. proc find_thread(name: cstring): thr_id {.importc, header: "<OS.h>".}
  365. proc getThreadId*(): int =
  366. ## Gets the ID of the currently running thread.
  367. if threadId == 0:
  368. threadId = int(find_thread(nil))
  369. result = threadId