Multithreading ";这";D中的指针和消息接收
D多线程模型不允许隐式内存共享,更喜欢消息传递和不可变数据。然而,编译器在接收消息时让Multithreading ";这";D中的指针和消息接收,multithreading,compiler-construction,this,d,Multithreading,Compiler Construction,This,D,D多线程模型不允许隐式内存共享,更喜欢消息传递和不可变数据。然而,编译器在接收消息时让这个指针通过似乎有些奇怪: import std.concurrency; import std.stdio; class Wat { int foo; Tid workerThread; this(int f) { foo = f; workerThread = spawn(&threadedWork); } //
这个指针通过似乎有些奇怪:
import std.concurrency;
import std.stdio;
class Wat {
int foo;
Tid workerThread;
this(int f)
{
foo = f;
workerThread = spawn(&threadedWork);
}
// Must be static. This makes sense because otherwise
// the object (via "this") would be accessible in two threads,
// and D discourages shared memory,
// preferring messages and immutable data.
static void threadedWork()
{
// Compiler correctly complains that I can't access a non-static function
// from inside a static one.
bar(42);
while (true) {
// But this is allowed. What gives?
receive (
&bar
);
}
}
void bar(int bar)
{
if (foo == bar)
writeln("The answer");
}
}
为什么编译器允许我在receive
中使用非静态函数?这是个bug吗?看起来像个bug。所发生的是&bar为您获取一个指向方法的指针,而该方法没有该指针,该指针的类型作为函数指针:
pragma(msg, typeof(&Wat.bar));
void function(int bar)
然后,std.concurrency.receive看到这一点并说“哦,这是一个int消息的处理程序”,然后接受它。。。。没有意识到它还需要一个隐藏的this参数来传递给它
如果您尝试使用它,如果它尝试访问任何类成员,您将得到一个随机结果/崩溃,因为this指针实际上没有传递给函数,因此它访问随机垃圾
所以,虽然我会说这是一个错误。。。我不确定那只虫子是什么。std.concurrency无法区分实void函数(int)和伪void函数,因为操作符的地址不转发关于隐藏this指针的信息。我认为这才是真正的问题。也谢谢你提交报告!