D中core.sync.condition的奇怪设计

问题描述 投票:1回答:1

在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)
    }
}

请赐教)

concurrency d
1个回答
0
投票

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的构造函数是共享的,所以我们需要将MutexCondition转换回shared,否则我们不能将它们分配给mtxcnd,因为构造函数是shared

© www.soinside.com 2019 - 2024. All rights reserved.