gpt4 book ai didi

scala - 了解并行存在并查找

转载 作者:行者123 更新时间:2023-12-04 04:31:46 24 4
gpt4 key购买 nike

我采用List[Int]并想搜索x值,其中x * 10 > 500并行。因此,如果列表包含任何大于或等于51的值,则exists应该返回true

def f(x: Int) = {
println("calculating for " + x)
Thread.sleep(100 - x)
println("finished " + x)
x * 10
}

val res = List.range(1, 100).par.exists(f(_) > 500)

结果如下:
calculating for 1
calculating for 25
calculating for 50
calculating for 75
calculating for 13
finished 75 // <-- first valid result found: 75 * 10 > 500
finished 50
calculating for 51 // but it kicks off more expensive calculations
finished 25
calculating for 26
finished 13
calculating for 14
finished 1
calculating for 2
finished 51
finished 26
calculating for 27 // and more
finished 14
calculating for 15
finished 2
calculating for 3
finished 27
calculating for 28
finished 15
calculating for 16
finished 3
calculating for 4 // and more...
finished 28
calculating for 29
finished 16
calculating for 17
finished 29
calculating for 30
finished 4
calculating for 5
finished 17
calculating for 18
finished 30
finished 5
calculating for 6
finished 18
finished 6
res: Boolean = true

我在Scala 2.9.1中使用双核计算机。

这里发生了什么?这按预期工作吗?为什么不立即将消息发送到其他线程以中止发现第一个结果的任务?如果 f是昂贵的计算,这可能会非常昂贵。
find似乎以相似的方式工作,搜索了更多的值,即使文档说“元素不一定是迭代顺序中的第一个此类元素”和“选择是不确定的”。

最佳答案

Why doesn't it just send out the message to the other threads to abort mission as soon as the first result is found?



因为那是不可能的。 JAVA不会让您那样做。或者,确实可以,但是已弃用。

参见(不推荐使用的) Thread.stop()的描述:

This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.



换句话说,由于带有锁的多线程代码本来就被破坏了,因此它们不赞成使用一种完美的方法,该方法可以愉快地用于不共享可变状态的线程,因此不需要锁定数据结构。

关于scala - 了解并行存在并查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8470162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com