这些线程安全吗?
今天参加一个面试,面试官问了我这样的问题:
重入和互斥线程安全吗?你能解释一下为什么吗?
我对并发编程比较陌生,无法回答。但我说……
互斥是线程安全的。但可重入则不然,这就是我们使用可重入锁的原因。
面试官继续讨论下一个问题,尽管到了另一个领域……我想我把这个问题搞砸了……
当他问我这个问题时,他希望我说什么?
I attended an interview today in which the interviewer asked me the following question :
Is re-entrancy and mutual exclusion thread-safe ? Can you explain why ?
I am relatively new to concurrent programming and could not answer it.. But i said ...
Mutual exclusion is thread safe . But re-entrancy is not and that is the reason why we have re-entrant locks .
The interviewer moved on to the next question though to a different area ... I think i messed this one up ...
What is he expecting me to say when he asked me this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正确的答案应该是:
是的,它们是线程安全的实现。
可重入
相互排斥
Proper answer should be:
Yes they are implementation of Thread safety.
re-entrancy
Mutual exclusion
两者都是线程安全的 - 您也可以在维基百科上阅读它:
http://en.wikipedia.org/wiki/Reentrant_(子例程)< br>
http://en.wikipedia.org/wiki/Mutual_exclusion
可重入互斥体是可以从同一线程多次锁定的互斥体,前提是确保每个锁都有相应的解锁。
Both are thread safe - you can read it also on Wikipedia:
http://en.wikipedia.org/wiki/Reentrant_(subroutine)
http://en.wikipedia.org/wiki/Mutual_exclusion
Re-entrant mutexes are mutexes that can be locked multiple times from the same thread if it is ensured that there's a corresponding unlock for each lock.
我引用http://en.wikipedia.org/wiki/Reentrant_(subroutine)
可重入和线程安全这两个概念都与函数处理资源的方式相关。然而,它们并不相同。
虽然可重入的概念会影响函数的外部接口,但线程安全仅涉及函数的实现,而不涉及其外部接口。
-- 在大多数情况下,要使不可重入函数可重入,必须修改其外部接口,以便所有数据都由函数的调用者提供。
-- 要使线程不安全的函数成为线程安全的,只需更改实现即可,通常通过添加同步块来保护共享资源免受不同线程的并发访问。
因此,可重入是比线程安全更基本的属性,并且根据定义,可重入导致线程安全:每个可重入函数都是线程安全的;然而,并非每个线程安全函数都是可重入的。
I quote http://en.wikipedia.org/wiki/Reentrant_(subroutine)
Both concepts of reentrancy and thread safety relate to the way functions handle resources. However, they are not the same.
While the concept of reentrancy can affect the external interface of a function, thread safety only concerns the implementation of the function and not its external interface.
-- In most cases, to make a non-reentrant function reentrant, its external interface must be modified such that all data is provided by the caller of the function.
-- To make a thread-unsafe function thread-safe, only the implementation needs to be changed, usually by adding synchronization blocks to protect shared resources from concurrent accesses by different threads.
Therefore, reentrancy is a more fundamental property than thread-safety and by definition, leads to thread-safety: Every reentrant function is thread-safe; however, not every thread-safe function is reentrant.