在D编程语言中,类Mutex
具有其方法的共享和非共享版本。这是合乎逻辑的 - 互斥线程在线程之间共享。但是类Condition
根本没有共享方法。为什么?也许我错过了什么,但对我来说这很奇怪,因为这样的代码不起作用:
class Foo {
private Mutex mtx;
private Condition cnd;
shared this() {
mtx = new Mutex(this); // error: no constructor Mutex(shared Object)
cnd = new Condition(mtx); // error: no constructor Condition(shared Mutex)
}
}
请赐教)
shared
是一个如此奇怪的野兽,基本上Mutex
只有构造,它采取Mutex
本身的共享对象,而Foo不是。
Condition
没有接受shared(Mutex)
的构造函数。
基本上你可以解决这个问题:
class Foo {
private Mutex mtx;
private Condition cnd;
shared this() {
mtx = cast(shared)new Mutex(cast() this);
cnd = cast(shared)new Condition(cast() mtx);
}
}
仅仅因为构造函数是像shared
那样的this() shared
然后它并不真正适用于任何传递给它的东西,基本上它只是它的身体AFAIK。
但是要详细说明上面的代码。
cast()
将丢弃应用于ex类型的任何属性。 shared
允许你将它传递给构造函数。
因为Foo
的构造函数是共享的,所以我们需要将Mutex
和Condition
转换回shared
,否则我们不能将它们分配给mtx
和cnd
,因为构造函数是shared
。