Examples/Illustration of Wait-free And Lock-free Algorithms

99封情书 提交于 2020-05-24 08:45:47

问题


I've read that wait-free causes all threads to finish independently and lock-free ensures the program as a whole completes. I couldn't quite get it. Can anyone give an example (java) illustrating this.

EDIT: Does lock-free mean a program without deadlock?


回答1:


If a program is lock-free, it basically means that at least one of its threads is guaranteed to make progress over an arbitrary period of time. If a program deadlocks, none of its threads (and therefore the program as a whole) cannot make progress - we can say it's not lock-free. Since lock-free programs are guaranteed to make progress, they are guaranteed to complete (assuming finite execution without exceptions).

Wait-free is a stronger condition which means that every thread is guaranteed to make progress over an arbitrary period of time, regardless of the timing/ordering of thread execution; and so we can say that the threads finish independently. All wait-free programs are lock-free.

I don't know offhand of any Java examples which illustrate this but I can tell you that lock-free/wait-free programs are typically implemented without locks, using low-level primitives such as CAS instructions.




回答2:


No, Lock-free means a program without locks. Although, a wait-free algorithm is also lock-free; however, vice versa doesn't hold. But, both are non-blocking algorithms, nonetheless.

This wiki entry is a great read to understand lock-free and wait-free mechanism.

Well, java.util.concurrent.atomic package is an example of lock-free programming on single variables. And in Java 7 ConcurrentLinkedQueue is an example of wait-free implementation.

For further insight, I would like you to read this article, Going atomic by Brian Goetz -- the guy who wrote Java Concurrency in Practice.




回答3:


From the weaker to the stronger condition:

A method is lock-free if it guarantees that infinitely often some method call finishes in a finite number of steps.

A method is wait-free if it guarantees that every call finishes its execution in a finite number of steps.

Clearly, any wait-free method implementation is also lock-free, but not vice versa. Lock-free algorithms admit the possibility that some threads could starve.

However, from a "Practical Perspective" there are many situations in which starvation, while possible, is extremely unlikely, so a fast lock-free algorithm may be more attractive than a slower wait-free algorithm.

NOTE: An even stronger property it is called "bounded wait-free" which means: there is a bound on the number of steps a method call can take.



来源:https://stackoverflow.com/questions/4211180/examples-illustration-of-wait-free-and-lock-free-algorithms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!