在 C# 中处理延迟初始化对象的线程安全方法是什么?假设我有以下Lazy构造:
Lazy<MyClass> lazy = new Lazy<MyClass>(() => MyClass.Create(), true);
Run Code Online (Sandbox Code Playgroud)
稍后,我可能想处置MyClass创建的实例。大多数现有的解决方案都推荐这样的内容:
if (lazy.IsValueCreated)
{
lazy.Value.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
但据我所知,IsValueCreated没有任何锁:https://referencesource.microsoft.com/#mscorlib/system/Lazy.cs,284
MyClass这意味着当我们检查 时,另一个线程可能正在初始化过程中IsValueCreated。在这种情况下,我们将观察IsValueCreated到错误,并最终泄漏资源。这里正确的做法是什么?还是我错过了一些微妙的细节?
我们如何使用TensorFlow有效地计算矩阵中的成对余弦距离?给定MxN矩阵,结果应该是MxM矩阵,其中位置处的元素[i][j]是输入矩阵中第i行和第j行/矢量之间的余弦距离.
这可以通过Scikit-Learn轻松完成,如下所示:
from sklearn.metrics.pairwise import pairwise_distances
pairwise_distances(input_matrix, metric='cosine')
Run Code Online (Sandbox Code Playgroud)
在TensorFlow中是否有等效的方法?
我预计以下内容会产生编译错误,但事实并非如此。有什么想法吗?
fun <T, U: T> foo(a: T, b: U) {
println("$a $b")
}
foo("bar", 123)
Run Code Online (Sandbox Code Playgroud)
如果我foo()使用显式类型参数调用,它将无法按预期编译:
foo<String, Int>("bar", 123)
Error: Kotlin: Type argument is not within its bounds: should be subtype of 'String'
Run Code Online (Sandbox Code Playgroud)