互斥体所有权队列顺序 [英] Mutex ownership queue order

查看:180
本文介绍了互斥体所有权队列顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,如果我有三个线程都通过互斥锁访问相同的互斥部分.

Say, if I have three threads that all access the same mutually exclusive part via a mutex.

让我给你这个例子.

第一个线程探测互斥锁并首先获取其所有权:

The first thread probes the mutex and gets its ownership first:

//THREAD 1
//TIME: 2013-03-13 01:00:00.000Z
WaitForSingleObject(hMutex, INFINITE);

//Performs the operation that lasts 50 ms

ReleaseMutex(hMutex);

然后10毫秒后,线程2也请求它:

Then 10 ms later the thread 2 also requests it:

//THREAD 2
//TIME: 2013-03-13 01:00:00.010Z
WaitForSingleObject(hMutex, INFINITE);
//Do work
ReleaseMutex(hMutex);

20毫秒后,线程3也请求它:

and 20 ms later thread 3 requests it as well:

//THREAD 3
//TIME: 2013-03-13 01:00:00.030Z
WaitForSingleObject(hMutex, INFINITE);
//Do work
ReleaseMutex(hMutex);

在这种情况下,我可以确定线程2将始终在线程3之前获得互斥体所有权(因为可以说是第一行"),还是在线程2和线程2之间获得所有权是完全任意的? 3?

In this situation, can I be sure that thread 2 will always get the mutex ownership before thread 3 (since it was "first in line" so to speak), or is it completely arbitrary who gets the ownership between threads 2 and 3?

如果互斥锁是任意的,如何确保第一个等待线程首先获得所有权?

And if it is arbitrary with mutexes, how to make sure that the first waiting thread gets the ownership first?

推荐答案

可以肯定地说,出于您的目的,它是任意的,即操作系统将唤醒等待Mutex的线程之一并将其授予线程,但是决定哪个线程是不确定的.

It's pretty safe to say that for your purpose it's arbitrary in the sense that the operating system will wake up one of the threads waiting for the Mutex and grant it to the thread, but the decision as to which thread is non-deterministic.

您可以使用全局优先级索引为线程之间的优先级实现自己的方案.然后,如果等待Mutex的线程中的一个不是在 in-in-line 中接收到的,它将立即放弃并继续等待,直到Mutex再次可用.应当重复此过程,直到获取Mutex为止,并且根据线程的优先级索引与全局索引相比,线程是 in-line-line .

You could implement your own scheme for priority between your threads using a global priority index. Then if one of the threads waiting for the Mutex receives it while not being first-in-line it gives it up right away and proceeds to wait until the Mutex becomes available again. This should repeat until the Mutex is acquired and the thread is first-in-line according to the priority index of the thread as compared to the global index.

这篇关于互斥体所有权队列顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆