LoginSignup
3
1

More than 5 years have passed since last update.

nimスレッド操作

Posted at

概要

nimのスレッド操作をコツコツと。
nimのコンパイルオプションに、--threads:onを指定する必要があるようです。

以下メモ

スレッド実行サンプル

import locks
import math
import os
block:
  var
    thr: array [0..4, Thread[tuple[a,b,c: int]]]
    L: Lock
  # 乱数初期化
  randomize()
  # スレッドとして実行する関数
  proc threadFunc(interval: tuple[a,b,c: int]) {.thread.} =
    for i in interval.a..interval.b:
      acquire(L) # lock stdout
      echo interval.a,"=>",i
      release(L)
      sleep(interval.c)
  # ロックの初期化
  initLock(L)
  # スレッドを複数実行
  for i in 0..high(thr):
    var sleepTime = random(1000.0).toInt + 1000
    # 関数へ渡す値をタプルで渡す
    createThread(thr[i], threadFunc, (i*10 , i*10+5 , sleepTime ))
  # スレッド終了待機
  joinThreads(thr)
(stdout)
30=>30
0=>0
20=>20
40=>40
10=>10
20=>21
30=>31
40=>41
0=>1
10=>11
20=>22
30=>32
40=>42
0=>2
20=>23
10=>12
30=>33
20=>24
40=>43
0=>3
30=>34
10=>13
20=>25
40=>44
30=>35
0=>4
10=>14
40=>45
0=>5
10=>15
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1