简体   繁体   English

获得pthread锁的优先级

[英]priority in getting the lock in pthreads

Let say i have a list List and i have pthread_t t1 that polls from the list and i have many other pthreads that insert elements to the list. 假设我有一个列表List ,我有从列表中轮询的pthread_t t1 ,还有许多其他将元素插入列表的pthread。 The list is locked with a lock listLock . 该列表由锁listLock锁定。 when t1 has the lock - if the list is empty he goes to sleep with pthread_cond_wait(..) and when a thread inserts to the list he signals him. t1拥有锁时-如果列表为空,则使用pthread_cond_wait(..)进入睡眠状态,并且当线程插入列表时,他向他发出信号。

my question is: if t1 is in wait state and there are many threads that are stuck in pthread_mutex_lock(&listLock) , when the lock will be unlocked, will t1 have a priority to get the lock or will he "fight" the other threads to get the lock? 我的问题是:如果t1处于等待状态,并且有很多线程卡在pthread_mutex_lock(&listLock) ,则当锁将被解锁时, t1将优先获得该锁,或者他将与其他线程“打架”。得到锁?

thank you 谢谢

It will fight, however it's a fair fight. 它会战斗,但这是公平的战斗。 All callers are put into a queue based on the order that they called the wait. 所有呼叫者根据呼叫等待的顺序进入队列。 It's completely deterministic. 这是完全确定性的。

However given the way that you're using things, you may possibly want to think about using a read/write lock. 但是,考虑到您使用事物的方式,您可能需要考虑使用读/写锁。 It allows N simultaneous readers, but anytime something tries to do a write it will lock everyone down until it's done. 它允许N个并发读取器,但是任何时候尝试写入时 ,它将锁定所有人,直到完成。

As Chris said, the threads will fairly fight for the mutex. 就像克里斯说的那样,线程将公平地争取互斥量。 However, you may control how fair is the scheduling of the threads by using threads attribute variables. 但是,您可以通过使用线程属性变量来控制线程调度的公平性。 The following two links you guide you in the advantages and drawbacks of using this mechanism. 以下两个链接可指导您使用此机制的优缺点。

Thread Scheduling with pthreads under Linux and FreeBSD 在Linux和FreeBSD下使用pthread进行线程调度

Basic Scheduling Functions 基本计划功能

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

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