d 语言并发与递归



我一直在尝试使用带有d语言的actor模型来实现阶乘函数。我的目标是使用 创建演员 单独计算每个部分 e 生成一个新的角色来制作下一个。我只是D的初学者,所以我只是在学习如何使用这种语言。我的目标是将阶乘实现扩展到更多。这只是一个测试。

这是我的问题:我正在尝试使用递归实现阶乘;事实函数将为行中的下一个数字创建一个新的事实线程,除非它已达到基本条件。

我的代码:

void fact(Tid tid)
{
        int fact = 1;
        receive
        (
        (int i)
        {
            if(i == 0)
            {
                writeln("End of recursion");
            }
            else
            {
                fact *= i;
                send(thisTid, i-1);
            }
        }
    );
    send(tid, fact);
}
void main()
{
        auto tid = spawn(&fact, thisTid);
        int x = 3;
        send(tid, x);
        auto fact = receiveOnly!(int);
        writeln(fact);
}

我什至不知道这是否可能,无论如何它不起作用。如果我尝试添加 spwn 实际上函数,它会返回以下错误:

src/main.d(62): Error: template std.concurrency.spawn does not match any function template declaration
/usr/include/x86_64-linux-gnu/dmd/phobos/std/concurrency.d(399): Error: template std.concurrency.spawn(T...) cannot deduce template function from argument types !()(int*,Tid)
src/main.d(63): Error: template std.concurrency.send does not match any function template declaration
/usr/include/x86_64-linux-gnu/dmd/phobos/std/concurrency.d(463): Error: template std.concurrency.send(T...) cannot deduce template function from argument types !()(_error_,int)

那么,有可能做我想做的事情吗?如何?如果没有,有没有计划让这样的事情成为可能?

请帮忙。

我在这里可能离谱很远,但从该错误消息来看,在我看来,dmd 在您调用 spawn 时没有使用您认为它正在使用的fact。您有几个名为 fact 的整数,尽管在这个示例中(显然减少了,因为它不是 400 行(它们都不会冲突,但在完整代码中,我的猜测是其中一个会冲突(因为如果&fact是一个intfact将是一个int*(。

尝试将函数重命名为阶乘或类似名称,并在适当的情况下更改spawn调用。确保不要更改整数。

对我来说

很好用。您使用的是哪个 DMD 版本?如果您还没有升级到 2.059,也许可以尝试升级到它。

(注意:我说它的工作原理是它可以编译和运行。它不会给出写入答案,因为fact在返回之前只会receive一个数字,所以它只返回三个。您需要循环使用receive(

admin@poita ~% cat test.d
import std.stdio;
import std.concurrency;
void fact(Tid tid)
{
    int fact = 1;
    receive
    (
        (int i)
        {
            if(i == 0)
            {
                writeln("End of recursion");
            }
            else
            {
                fact *= i;
                send(thisTid, i-1);
            }
        }
    );
    send(tid, fact);
}
void main()
{
    auto tid = spawn(&fact, thisTid);
    int x = 3;
    send(tid, x);
    auto fact = receiveOnly!(int);
    writeln(fact);
}
admin@poita ~% dmd test.d
admin@poita ~% ./test
3
admin@poita ~%

最新更新