threads.nim 14 KB

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