# threads

- マニュアル
- 標準ライブラリ
- 索引

検索
分類:

Thread support for Nim.

Note: This is part of the system module. Do not import it directly. To activate thread support you need to compile with the `--threads:on` command line switch.

Nim's memory model for threads is quite different from other common programming languages (C, Pascal): Each thread has its own (garbage collected) heap and sharing of memory is restricted. This helps to prevent race conditions and improves efficiency. See the manual for details of this memory model.

# Examples

    import locks

    var
      thr: array[0..4, Thread[tuple[a,b: int]]]
      L: Lock

    proc threadFunc(interval: tuple[a,b: int]) {.thread.} =
      for i in interval.a..interval.b:
        acquire(L) # lock stdout
        echo i
        release(L)

    initLock(L)

    for i in 0..high(thr):
      createThread(thr[i], threadFunc, (i*10, i*10+5))
    joinThreads(thr)

# 型

    Thread*[TArg] {...}{.pure, final.} = object
      core: PGcThread
      sys: SysThread
      when TArg is void:
          dataFn: proc () {...}{.nimcall, gcsafe.}

      else:
          dataFn: proc (m: TArg) {...}{.nimcall, gcsafe.}
          data: TArg

  ソース 編集

# プロシージャ

    proc onThreadDestruction*(handler: proc () {...}{.closure, gcsafe.})

  Registers a thread local handler that is called at the thread's destruction.

  A thread is destructed when the `.thread` proc returns normally or when it raises an exception. Note that unhandled exceptions in a thread nevertheless cause the whole process to die.

  ソース 編集

    proc running*[TArg](t: Thread[TArg]): bool {...}{.inline.}

  Returns true if `t` is running. ソース 編集

    proc handle*[TArg](t: Thread[TArg]): SysThread {...}{.inline.}

  Returns the thread handle of `t`. ソース 編集

    proc joinThread*[TArg](t: Thread[TArg]) {...}{.inline.}

  Waits for the thread `t` to finish. ソース 編集

    proc joinThreads*[TArg](t: varargs[Thread[TArg]])

  Waits for every thread in `t` to finish. ソース 編集

    proc createThread*[TArg](t: var Thread[TArg];
                            tp: proc (arg: TArg) {...}{.thread, nimcall.}; param: TArg)

  Creates a new thread `t` and starts its execution.

  Entry point is the proc `tp`. `param` is passed to `tp`. `TArg` can be `void` if you don't need to pass any data to the thread.

  ソース 編集

    proc pinToCpu*[Arg](t: var Thread[Arg]; cpu: Natural)

  Pins a thread to a CPU.

  In other words sets a thread's affinity. If you don't know what this means, you shouldn't use this proc.

  ソース 編集

    proc createThread*(t: var Thread[void]; tp: proc () {...}{.thread, nimcall.})

  ソース 編集

    proc getThreadId*(): int

  Gets the ID of the currently running thread. ソース 編集