有人可以解释Mutex及其使用方法吗?

Sim*_*ons 6 c++ windows multithreading mutex

我阅读了一些关于Mutex的文档,但我唯一的想法是它有助于防止线程访问已被其他资源使用的资源.

我从Code片段获得并执行哪个工作正常:

#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");

}
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*ich 11

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

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

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

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

如果您正在使用的数据库本身不支持多线程访问,则此处仅需要互斥锁.