Can someone Explain Mutex and how it is used?

爷,独闯天下 提交于 2019-12-19 07:27:09

问题


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?


回答1:


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.

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

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.

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




回答2:


Maybe It will be the best source to you

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




回答3:


This link in 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,...

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.




回答4:


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

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



来源:https://stackoverflow.com/questions/3528877/can-someone-explain-mutex-and-how-it-is-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!