我目前有两个这样的函数共享同一个互斥量。
void fooA()
{
{
std::lock_guard<std::mutex> guard(myMutex);
doWork()
}
}
void fooB()
{
{
std::lock_guard<std::mutex> guard(myMutex);
doWork()
}
}
我的问题是,是否可以指定 fooA()
互斥量应优先/优先?
我知道互斥量是先到先得。假设有四个线程 t1、t2、t3、t4。现在假设线程 t1 当前拥有 fooB() 中的互斥量,t2 和 t3 正在排队等待 fooB()
中的互斥量,而线程 t4 正在排队等待 fooA( )
。我希望线程 t4 在访问 fooA()
后获得优先权,并让 t2、t3 继续等待。所有这些都应该在 t1 释放互斥量之后完成
最佳答案
考虑到您的问题不在于进程内运行的函数的 MUTEX 锁,而是多线程环境中的优先级排队,只要您有权访问线程创建函数——设置每个调用的优先级线程,你可以使用:
#include <sched.h>
int sched_setscheduler(pid_t pid, int policy,
const struct sched_param *param);
int sched_getscheduler(pid_t pid);
struct sched_param {
...
int sched_priority;
...
};
您可能会遇到的一些问题是 (1) 如果新生成的优先级线程然后在不给低优先级线程机会的情况下征用互斥量。 (2) 如果将多个线程设置为相同的高优先级(可以通过更正此设置或设置循环调度方案来覆盖) (3) 优先级倒置仍然是可能的。 这是我的第一个 SO 答案,希望对您有所帮助!如果您想了解更多信息,请查看引用资料,尤其是 (2),它给出了这个问题的原始答案!
引用资料: (1) https://linux.die.net/man/2/sched_setscheduler (2) How to give priority to privileged thread in mutex locking? (3) https://www.ibm.com/docs/en/aix/7.2?topic=programming-synchronization-scheduling
关于multithreading - 授予对 std::mutex 的优先访问权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68766226/