本文介绍了有人可以在有关 bInitialOwner 标志的 MSDN CreateMutex() 文档中解释此评论吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN CreatMutex() 文档(http://msdn.microsoft.com/en-us/library/ms682411%28VS.85%29.aspx) 在结尾处包含以下注释:

The MSDN CreatMutex() documentation (http://msdn.microsoft.com/en-us/library/ms682411%28VS.85%29.aspx) contains the following remark near the end:

两个或多个进程可以调用 CreateMutex 来创建同名的互斥锁.第一个进程实际上创建了互斥锁,具有足够访问权限的后续进程只需打开现有互斥锁的句柄.这使多个进程能够获得同一个互斥锁的句柄,同时减轻用户确保首先启动创建进程的责任.使用此技术时,您应该将 bInitialOwner 标志设置为 FALSE;否则,很难确定哪个进程拥有初始所有权.

有人可以解释使用 bInitialOwner = TRUE 的问题吗?

Can somebody explain the problem with using bInitialOwner = TRUE?

在前面的文档中,它建议调用 GetLastError() 将允许您确定对 CreateMutex() 的调用是否创建了互斥锁或只是返回了现有互斥锁的新句柄:

Earlier in the same documentation it suggests a call to GetLastError() will allow you to determine whether a call to CreateMutex() created the mutex or just returned a new handle to an existing mutex:

返回值

如果函数成功,则返回值是新创建的互斥对象的句柄.

If the function succeeds, the return value is a handle to the newly created mutex object.

如果函数失败,返回值为NULL.要获取扩展错误信息,请调用 GetLastError.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

如果互斥体是命名互斥体并且对象在此函数调用之前已存在,则返回值是现有对象的句柄,GetLastError 返回 ERROR_ALREADY_EXISTS,忽略 bInitialOwner,并且不授予调用线程所有权.但是,如果调用方的访问权限有限,则该函数将失败并显示 ERROR_ACCESS_DENIED,调用方应使用 OpenMutex 函数.

If the mutex is a named mutex and the object existed before this function call, the return value is a handle to the existing object, GetLastError returns ERROR_ALREADY_EXISTS, bInitialOwner is ignored, and the calling thread is not granted ownership. However, if the caller has limited access rights, the function will fail with ERROR_ACCESS_DENIED and the caller should use the OpenMutex function.

推荐答案

使用 bInitialOwner 将两步合二为一:创建互斥锁和获取互斥锁.如果多人可以同时创建互斥锁,则第一步可能会失败,而第二步可能会成功.

Using bInitialOwner combines two steps into one: creating the mutex and acquiring the mutex. If multiple people can be creating the mutex at once, the first step can fail while the second step can succeed.

正如其他回答者所提到的,这严格不是问题,因为如果其他人先创建它,您将得到 ERROR_ALREADY_EXISTS.但是,您必须仅通过使用错误代码来区分无法创建或找到互斥锁"和无法获取互斥锁;稍后再试"的情况.它会使您的代码难以阅读且更容易搞砸.

As the other answerers mentioned, this isn't strictly a problem, since you'll get ERROR_ALREADY_EXISTS if someone else creates it first. But then you have to differentiate between the cases of "failed to create or find the mutex" and "failed to acquire the mutex; try again later" just by using the error code. It'll make your code hard to read and easier to screw up.

相比之下,当 bInitialOwner 为 FALSE 时,流程要简单得多:

In contrast, when bInitialOwner is FALSE, the flow is much simpler:

result = create mutex()
if result == error:
   // die
result = try to acquire mutex()
if result == error:
   // try again later
else:
   // it worked!

这篇关于有人可以在有关 bInitialOwner 标志的 MSDN CreateMutex() 文档中解释此评论吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:15