gpt4 book ai didi

winapi - 有人可以在有关 bInitialOwner 标志的 MSDN CreateMutex() 文档中解释此评论吗?

转载 作者:行者123 更新时间:2023-12-03 18:37:55 26 4
gpt4 key购买 nike

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

Two or more processes can call CreateMutex to create the same named mutex. The first process actually creates the mutex, and subsequent processes with sufficient access rights simply open a handle to the existing mutex. This enables multiple processes to get handles of the same mutex, while relieving the user of the responsibility of ensuring that the creating process is started first. When using this technique, you should set the bInitialOwner flag to FALSE; otherwise, it can be difficult to be certain which process has initial ownership.



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

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

Return Value

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

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

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 将两步合二为一:创建互斥锁和获取互斥锁。如果多人可以同时创建互斥锁,则第一步可能会失败,而第二步可能会成功。

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

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

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

关于winapi - 有人可以在有关 bInitialOwner 标志的 MSDN CreateMutex() 文档中解释此评论吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2966654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com