我想重载 Dart 中的比较运算符 (==) 来比较结构。现在,当我已经重载基类的比较运算符并想要重用它时,我不确定如何为派生类执行此操作。
假设我有一个基类,如:
class Base
{
int _a;
String _b;
bool operator ==(Base other)
{
if (identical(other, this)) return true;
if (_a != other._a) return false;
if (_b != other._b) return false;
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我声明我的派生类添加了额外的字段,并且还想重载 operator==。我只想比较派生类中的附加字段,并将 Base 字段的比较委托给 Base 类。在其他编程语言中,我可以执行类似Base::operator==(other)或 的操作super.equals(other),但在 Dart 中我不知道什么是最好的方法。
class Derived extends Base
{
int _c; // additional field
bool operator ==(Derived other)
{
if (identical(other, this)) return true;
if (_c != other._c) return false; // Comparison …Run Code Online (Sandbox Code Playgroud) 我目前正在构建一个系统,其中有多个线程正在运行,一个线程可以将工作排队到另一个线程并等待完成。我使用互斥体和条件变量进行同步。为了避免为每个操作创建新的互斥体和 cv,我想对其进行优化,并尝试为每个正在等待的线程使用 thread_local 互斥体/cv 对。然而,这出乎意料地不起作用,我很有趣为什么。
基本上我的代码将工作排队到另一个线程并等待它,如下所示:
/* thread_local */ std::mutex mtx;
/* thread_local */ std::condition_variable cv;
bool done = false;
io_service.post([&]() {
// Execute the handler in context of the io thread
functionWhichNeedsToBeCalledInOtherThread();
// Signal completion to unblock the waiter
{
std::lock_guard<std::mutex> lock(mtx);
done = true;
}
cv.notify_one();
});
// Wait until queued work has been executed in io thread
{
std::unique_lock<std::mutex> lk(mtx);
while (!done) cv.wait(lk);
}
Run Code Online (Sandbox Code Playgroud)
如果同步对象不是,则此方法可以正常工作thread_local。当我添加thread_local等待线程时,它会永远等待,这表明条件变量永远不会发出信号。我现在有一种感觉,尽管通过引用捕获对象,但另一个线程的 thread_local 对象在 lambda 内部使用。mtx我什至可以通过检查lambda 内部和外部的地址来确认捕获没有执行正确的操作-> 它们不匹配。 …