我有一个线程间通信问题的简单例子:我想随时随地运行""后台线程中的算法。随时算法逐步地执行结果类型T
的一些计算,即,它偶尔产生更新,更精确的结果。用Nim的说法,它们最好用迭代器代表。在主线程中,我现在想要在它自己的线程中包含这些迭代器,并且有可能在线程中查询诸如&#34之类的东西;是否有可用的新值"或者"当前的计算结果是什么"。
由于我不熟悉Nim的并发概念,因此无法实现所需的线程间通信。我的想法是使用TChannel
进行沟通。根据{{3}},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"
不幸的是,这没有预期的行为,即我从未在主线程中收到任何内容。 IRC告诉我,问题是我不使用全局变量。但即使经过很长一段时间的思考,我也没有确切地看到为什么会失败,也没有办法解决它。问题是我不能简单地将变量thread
和channel
设为全局变量,因为它们取决于类型T
。我还想避免将此限制为仅运行单个随时算法(或其他一些固定数N)。我还被告知这种方法总体上没有意义,所以也许我只是错过了这个问题有一个完全不同的解决方案?
答案 0 :(得分:3)
您在发送和接收中使用了两个不同的频道。
Nim中的对象分配是深层复制,它们是不同的对象。
var channel = args.channel[]
和
result = channel
要解释它,请参阅下面的代码段:
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
要将频道作为参数传递并返回值,请参阅Nim forum中的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()
输出:
main thread send: 0
0
main thread send: 1
1
main thread send: 2
2
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()