Using Mutex Objects (MSDN2001)
来源:互联网 发布:mac 解压rar 编辑:程序博客网 时间:2024/05/18 04:25
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 mutexif (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; }
- Using Mutex Objects (MSDN2001)
- Using Mutex Objects
- Mutex Objects
- Using Event Objects
- Using Semaphore Objects
- Using Vertex Buffer Objects
- 2: Making & Using Objects
- Using SQLExec and Record Objects
- Java - Saving Objects Using DBObject
- Using C++ objects in Delphi
- VC6.0MSDN2001
- Practice of using spinlock instead of mutex
- Using Struts With Java Data Objects
- Pattern matching on Java objects using Tom
- Using and Understanding Java Data Objects
- chap 2 making and using objects
- Understanding and Using OpenGL Texture Objects
- Using Record Objects as Parameters and Returns
- Spring+quartz+我犯的傻
- Linux驱动学习--时间、延迟及延缓操作(转载)
- hibernate N+1问题
- 韩语键盘及打字技巧
- Oracle Enterprise Linux/Redhat Linux 6.0 U盘安装方法
- Using Mutex Objects (MSDN2001)
- erlang和as3 socket的二进制通信
- asp.net常用方法
- 追寻理想主义
- 查看oracle当前连接数
- 使用 JET模板的一些约定
- POJ3302 Subsequence
- mysql 的 if 简单介绍
- SAAS数据安全是问题吗?