Why await of Condition releases the lock but signal does not?

两盒软妹~` 提交于 2019-12-04 12:56:40

You have missed this sentence in Contition#await:

In all cases, before this method can return the current thread must re-acquire the lock associated with this condition. When the thread returns it is guaranteed to hold this lock.

In other words, you must explicitly release the lock after await, just as with signal.

Why this mechanism is sound: if you first released the lock, then signaled, you'd be open to race conditions where other threads made changes between releasing the lock and the signal reaching a parked thread. The way the mechanism works, first a definite thread is chosen to be awoken by the signal, then it waits for the lock, then the signaling thread releases it, then the awoken thread goes on.

You might argue that signal could do all of this internally, but then:

  1. the API would become confusing: there would be more than one method releasing the lock;
  2. the APi would become more restrictive and preclude any use cases where the thread wants to do something more before releasing the lock, such as atomically issuing more signals.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!