windows 有人可以解释互斥锁以及它是如何使用的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3528877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:04:24  来源:igfitidea点击:

Can someone Explain Mutex and how it is used?

c++windowsmultithreadingmutex

提问by Simsons

I read a few documents about Mutex and still the only Idea I have got is that it helps preventing threads from accessing a resource that is already being used by another resource.

我阅读了一些关于互斥锁的文档,但我唯一的想法是它有助于防止线程访问已被另一个资源使用的资源。

I got from Code snippet and executed which works fine:

我从代码片段中获取并执行,效果很好:

#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;


BOOL FunctionToWriteToDatabase(HANDLE hMutex)
{
    DWORD dwWaitResult;
    // Request ownership of mutex.
    dwWaitResult = WaitForSingleObject(
    hMutex, // handle to mutex
    5000L); // five-second time-out interval
        switch (dwWaitResult)
        {
        // The thread got mutex ownership.
            case WAIT_OBJECT_0:
            __try
            {
                // Write to the database.
            }
            __finally {
            // Release ownership of the mutex object.
            if (! ReleaseMutex(hMutex)) {
            // Deal with error.
        }
            break;
        }
            // Cannot get mutex ownership due to time-out.
            case WAIT_TIMEOUT:
            return FALSE;
            // Got ownership of the abandoned mutex object.
            case WAIT_ABANDONED:
            return FALSE;
        }
    return TRUE;
}

void main()
{
    HANDLE hMutex;

    hMutex=CreateMutex(NULL,FALSE,"MutexExample");

    if (hMutex == NULL)
    {
        printf("CreateMutex error: %d\n", GetLastError() );
    }
    else if ( GetLastError() == ERROR_ALREADY_EXISTS )
        printf("CreateMutex opened existing mutex\n");

    else
        printf("CreateMutex created new mutex\n");

}

But What I don't understand is where is the thread and where is the shared resource? Can anyone please explain or provide a better article or document?

但我不明白的是线程在哪里,共享资源在哪里?任何人都可以解释或提供更好的文章或文件吗?

回答by Chris Schmich

A mutex provides mutually exclusive access to a resource; in your case, a database. There aren't multiple threads in your program, but you can have multiple instances of your program running, which is what your mutex is protecting against. Effectively, it is still protecting against access from more than one thread, it's just that those threads can be in separate processes.

互斥提供MUTually对资源clusive访问; 在你的情况下,一个数据库。您的程序中没有多个线程,但是您可以运行多个程序实例,这是您的互斥锁所防止的。实际上,它仍然可以防止来自多个线程的访问,只是这些线程可以位于不同的进程中。

Your code is creating a namedmutex that can be shared across multiple instances of your application. This is a form of interprocess communication. MSDN documentation on CreateMutexhas additional helpful information about named mutexes:

您的代码正在创建一个可在应用程序的多个实例之间共享的命名互斥锁。这是进程间通信的一种形式。MSDN 文档中CreateMutex有关于命名互斥体的其他有用信息:

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...

Multiple processes can have handles of the same mutex object, enabling use of the object for interprocess synchronization.

两个或多个进程可以调用 CreateMutex 来创建同名互斥锁。第一个进程实际上创建了互斥锁,具有足够访问权限的后续进程只需打开现有互斥锁的句柄......

多个进程可以拥有同一个互斥对象的句柄,从而可以使用该对象进行进程间同步。

A mutex is only necessary here if the database you're working against doesn't inherently support multithreaded access.

仅当您使用的数据库本身不支持多线程访问时,才需要互斥锁。

回答by Hwansoo Kim

Maybe It will be the best source to you

也许它会是你最好的资源

http://en.wikipedia.org/wiki/Mutual_exclusion

http://en.wikipedia.org/wiki/Mutual_exclusion

回答by stefaanv

This linkin msdn provides a similar example as yours with threads made in the main() function. But again the shared resource, which is supposed to be a database is not included.
Anyway, a shared resource is whatever that needs to be accessed from multiple threads: settingsfiles, drivers, database,...

msdn 中的此链接提供了与您在 main() 函数中创建的线程类似的示例。但同样不包括应该是数据库的共享资源。
无论如何,共享资源是需要从多个线程访问的任何内容:设置文件、驱动程序、数据库……

Mind you that the counter in the example is written while protected by the mutex, while it is been read while not being protected. While in this case, there is probably no problem, it is a bit sloppy.

请注意,示例中的计数器在受互斥锁保护时被写入,而在不受保护时被读取。虽然在这种情况下,可能没有问题,但有点马虎。

回答by ckv

You can refer this SO post for comparison of various thread synchronization mechanisms Difference between Locks, Mutex and Critical Sections

您可以参考这篇 SO post 来比较各种线程同步机制 Locks, Mutex 和 Critical Sections之间的差异

If you want specific information Mutex then wikipedia will give you enough details.

如果您想要特定信息 Mutex,那么维基百科将为您提供足够的详细信息。