简体   繁体   English

C中互斥锁返回的顺序

[英]Order of mutex_lock return in C

Lets say there are 3 threads A, B and C. And a mutex X 假设有3个线程A,B和C。还有一个互斥锁X

A calls pthread_mutex_lock on X. A在X上调用pthread_mutex_lock。

B calls pthread_mutex_lock on X. B在X上调用pthread_mutex_lock。

* *

C calls pthread_mutex_lock on X. C在X上调用pthread_mutex_lock。

A calls pthread_mutex_unlock on X. A在X上调用pthread_mutex_unlock。

** **

Who will now be able to use the shared resource first? 现在谁将可以首先使用共享资源? B or C? B还是C? And what happens if I try to use pthread_destroy_mutex in *? 如果我尝试在*中使用pthread_destroy_mutex,会发生什么? in **? 在**?

Who will now be able to use the shared resource first?

That depends on the kernel scheduler implementation. 那取决于内核调度程序的实现。 Posix words it this way: Posix这样说:

If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock() is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex. 如果在调用pthread_mutex_unlock()时互斥对象引用的互斥对象上有阻塞的线程,导致互斥变得可用,则调度策略将确定哪个线程应获取该互斥。

And what happens if I try to use pthread_destroy_mutex in *? in **?

Again from the manual : 再次从手册

Attempting to destroy a locked mutex results in undefined behavior. 尝试销毁锁定的互斥锁会导致未定义的行为。

If you have any further doubts along these lines then suggest consulting the relevant man pages. 如果您对这些方面还有任何疑问,则建议查阅相关的手册页。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM