threads.nim 14 KB

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