LoginSignup
3
3

More than 5 years have passed since last update.

nimでchannelを用いて他スレッドと連携

Last updated at Posted at 2018-06-22

概要

Nimで他のスレッドとチャンネルを用いて連携


シンプルデモ

import os
import threadpool
var channel: TChannel[int]

# バッファのデータを全て読み込み
proc recved():seq[int] =
  result = @[]
  while channel.peek() > 0:
    result.add(channel.recv())

# 5度データ送信 
proc sendMsg() {.thread.} =
  for i in 0..<5:
    channel.send(i)

channel.open()
spawn sendMsg()
sleep(1000)
echo recved() # @[0, 1, 2, 3, 4]
sync()

オープン

import threadpool
var channel: TChannel[int]
#送受信の前にチャンネルを開く必要有り
channel.open()

クローズ

import threadpool
var channel: TChannel[int]
#チャンネルを閉じ、リソースを開放
channel.close()

送受信

import threadpool
var channel: TChannel[int]
channel.open()
channel.send(37)
#バッファのデータを一つ返す
#データがない場合、受信するまでブロッキング
echo channel.recv(37) # 0

バッファのデータ数

import threadpool
var channel: TChannel[int]
#チャンネルが閉じていた場合-1を返す
channel.peek()

参考

Module channels

3
3
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
3