Using Mutex Objects (MSDN2001)

Using Mutex Objects

You can use a mutex object to protect a shared resource from simultaneous access by multiple threads or processes. Each thread must wait for ownership of the mutex before it can execute the code that accesses the shared resource. For example, if several threads share access to a database, the threads can use a mutex object to permit only one thread at a time to write to the database.
In the following example, a process uses the CreateMutex function to create a named mutex object or open a handle to an existing mutex object.

HANDLE hMutex; 

// Create a mutex with no initial owner.

hMutex = CreateMutex( 
    NULL,                       // no security attributes
    FALSE,                      // initially not owned
    "MutexToProtectDatabase");  // name of mutex

if (hMutex == NULL) 
{
    // Check for error.
}

 

When a thread of this process writes to the database, as in the next example, it first requests ownership of the mutex. If it gets ownership, the thread writes to the database and then releases its ownership.
The example uses structured exception-handling syntax to ensure that the thread properly releases the mutex object. The __finally block of code is executed no matter how the __try block terminates (unless the __try block includes a call to the TerminateThread function). This prevents the mutex object from being abandoned inadvertently.

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; 
}


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值