简体   繁体   中英

Locking and synchronization using Mutex

I am creating a program that will run the same function in several processes and several threads so I created a function to achieve locking and synchronization which is

HANDLE WaitOnMutex(char* mt)
{
    HANDLE ghMutex=NULL; 
    DWORD lastError=-1;
    do
    {
        ghMutex = CreateMutex(NULL,TRUE,mt);
        lastError=  GetLastError();
        if(lastError!=ERROR_SUCCESS)
        {
            CloseHandle(ghMutex);
            Sleep(2000);
        }
    }
    while(lastError!=ERROR_SUCCESS);
    return ghMutex;
}

and I am using it like the following

    HANDLE mtx=WaitOnMutex("Global\\DBG_MY_APP");
    //Do the work that needs sync
    CloseHandle(mtx)

Is this a proper way to lock this function ? or do I need to use a different method..

Note: I am using "Global" because some parts of my app is winService and I need to lock between session-Isolated processes

The code is working in testing environment, but I am not sure if I am doing it the right way

What you have coded is a busy wait, which is less than ideal under most circumstances. Not only that, but you've wrapped it in heavyweight mutex creation and release calls.

To use a named mutex for cross-process synchronization, each process should call CreateMutex only once. You then keep the mutex handle around, and use WaitForSingleObject to wait for it and ReleaseMutex to release the lock. You can then lock it again with WaitForSingleObject next time you need to access the protected resource, and so forth.

When your process is done with the mutex "forever" (eg because the process is exiting) then you call CloseHandle .

I guess this will sort of work, for a sufficiently loose definition of "work". It's not how I'd do the job though.

I think I'd do things more like this:

Somewhere in one-time initialization code:

HANDLE mutex = CreateMutex(name); // yes, there are more parameters here.

Then to write to the log:

WaitForSingleObject(mutex, INFINITE);

// write to log

ReleaseMutex(handle);

Then during one-time shut-down code:

CloseHandle(mutex);

If you're using C++ instead of C, you usually want to handle this via RAII though, so you'd create a log object that does the CreateMutex call in its ctor, and the CloseHandle call in it dtor. Then you'd have a write functor that does the WaitForSingleObject in its ctor, writes to the log in its operator() , and does the ReleaseMutex in its dtor. This keeps most of your code relatively simple, and maintains exception safety with little or no extra work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM