代码之家  ›  专栏  ›  技术社区  ›  Simsons

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

  •  6
  • Simsons  · 技术社区  · 14 年前

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

    我从代码片段中获取并执行了一个很好的代码:

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

    但我不明白的是,线程在哪里,共享资源在哪里?有人能解释一下或者提供一个更好的文章或者文件吗?

    4 回复  |  直到 12 年前
        1
  •  12
  •   Chris Schmich    8 年前

    互斥提供 精神上 前任 对资源的决定性访问;在您的例子中是数据库。程序中没有多个线程,但是可以运行多个程序实例,这是互斥锁所要保护的。实际上,它仍然在防止来自多个线程的访问,只是这些线程可以在不同的进程中。

    您的代码正在创建 命名 CreateMutex 包含有关命名互斥体的其他有用信息:

    两个或多个进程可以调用 互斥。第一个过程实际上 创建互斥体,然后 权限只需打开

    多个进程可以有 相同的互斥对象,允许使用 进程间的对象 同步。

        2
  •  0
  •   Hwansoo Kim    14 年前
        3
  •  0
  •   Community CDub    4 年前

    这个 link
    不管怎样,共享资源就是需要从多个线程访问的资源:设置文件、驱动程序、数据库,。。。

        4
  •  -1
  •   Community CDub    8 年前

    您可以参考这篇文章来比较各种线程同步机制 Difference between Locks, Mutex and Critical Sections

    如果你想要特定的信息互斥,那么维基百科会给你足够的细节。