blu*_*e10 9 concurrency nim-lang
我有一个线程间通信问题的简单示例:我想在后台线程中运行任意"随时"算法.随时算法T逐步地执行结果类型的一些计算,即,它偶尔产生更新,更精确的结果.用Nim的说法,它们最好用迭代器代表.在主线程中,我现在想要将这些迭代器包装在它自己的线程中,并且有可能在线程中查询"是否有新值可用"或"当前计算结果是什么".
由于我不熟悉Nim的并发概念,因此无法实现所需的线程间通信.我的想法是使用a TChannel进行通信.根据这个论坛帖子,一个TChannel不能与之结合使用spawn但需要使用createThread.我设法得到以下内容来编译和运行:
import os, threadpool
proc spawnBackgroundJob[T](f: iterator (): T): TChannel[T] =
type Args = tuple[iter: iterator (): T, channel: ptr TChannel[T]]
# I think I have to wrap the iterator to pass it to createThread
proc threadFunc(args: Args) {.thread.} =
echo "Thread is starting"
let iter = args.iter
var channel = args.channel[]
for i in iter():
echo "Sending ", i
channel.send(i)
var thread: TThread[Args]
var channel: TChannel[T]
channel.open()
let args = (f, channel.addr)
createThread(thread, threadFunc, args)
result = channel
# example use in some main thread:
iterator test(): int {.closure.} =
sleep(500)
yield 1
sleep(500)
yield 2
var channel = spawnBackgroundJob[int](test)
for i in 0 .. 10:
sleep(200)
echo channel.peek()
echo "Finished"
Run Code Online (Sandbox Code Playgroud)
不幸的是,这没有预期的行为,即我从未在主线程中收到任何内容.IRC告诉我,问题是我不使用全局变量.但即使经过很长一段时间的思考,我也没有确切地看到为什么会失败,也没有办法解决它.问题是我不能简单地使变量thread和channel全局变量,因为它们取决于类型T.我还想避免将此限制为仅运行单个随时算法(或其他一些固定数N).我还被告知这种方法总体上没有意义,所以也许我只是错过了这个问题有一个完全不同的解决方案?
您在 send 和 receive 中使用两个不同的通道。
Nim 中的对象分配是深复制,它们是不同的对象。
var channel = args.channel[]
Run Code Online (Sandbox Code Playgroud)
和
result = channel
Run Code Online (Sandbox Code Playgroud)
为了解释它,请参见下面的代码片段:
type
A = object
x: int
y: int
var a,b: A
var c = cast[ptr A](allocShared0(sizeof(A))) # shared memory allocation
a = c[]
b = c[]
echo a.x, a.y, b.x, b.y, c.x, c.y # output: 000000
a.x = 1
a.y = 2
echo a.x, a.y, b.x, b.y, c.x, c.y # output: 120000
b.x = 3
b.y = 4
echo a.x, a.y, b.x, b.y, c.x, c.y # output: 123400
Run Code Online (Sandbox Code Playgroud)
要将 Channel 作为参数和返回值传递,请参考Nim 论坛Jehan 的答案。
将 Jehan 的答案粘贴到此处以供快速参考,并使其在 Nim 0.11.2 中编译通过
type SharedChannel[T] = ptr TChannel[T]
proc newSharedChannel[T](): SharedChannel[T] =
result = cast[SharedChannel[T]](allocShared0(sizeof(TChannel[T])))
open(result[])
proc close[T](ch: var SharedChannel[T]) =
close(ch[])
deallocShared(ch)
ch = nil
proc send[T](ch: SharedChannel[T], content: T) =
ch[].send(content)
proc recv[T](ch: SharedChannel[T]): T =
result = ch[].recv
proc someThread(ch: (SharedChannel[string], SharedChannel[bool])) {.thread.} =
let (mainChannel, responseChannel) = ch
while true:
let s = mainChannel.recv
if s == nil:
break
echo s
responseChannel.send(true)
responseChannel.send(false)
proc main() =
var
mainChannel = newSharedChannel[string]()
responseChannel = newSharedChannel[bool]()
th: TThread[(SharedChannel[string], SharedChannel[bool])]
createThread(th, someThread, (mainChannel, responseChannel))
for i in 0..2:
echo("main thread send: " & $i)
mainChannel.send($i)
if not responseChannel.recv:
break
mainChannel.send(nil)
joinThread(th)
close(mainChannel)
close(responseChannel)
main()
Run Code Online (Sandbox Code Playgroud)
输出:
main thread send: 0
0
main thread send: 1
1
main thread send: 2
2
Run Code Online (Sandbox Code Playgroud)
import os, threadpool, macros
template spawnBackgroundJob(t: typedesc, chan:ptr TChannel[t], iter: expr): stmt {.immediate.}=
block:
proc threadFunc(channel: ptr TChannel[t]) {.thread.} =
echo "Thread is starting"
for i in iter:
echo "Sending ", i
channel[].send(i)
channel[].open()
var thread: TThread[ptr TChannel[t]]
createThread(thread, threadFunc, chan)
#joinThread(thread)
# example use in some main thread:
iterator testJob(): int =
yield 0
sleep(500)
yield 1
sleep(500)
yield 2
var channel: ptr TChannel[int]
channel = cast[ptr TChannel[int]](allocShared0(sizeof(TChannel[int])))
spawnBackgroundJob(type(int), channel, testJob())
for i in 1 .. 10:
sleep(200)
echo channel[].peek()
channel[].close()
Run Code Online (Sandbox Code Playgroud)