> For the complete documentation index, see [llms.txt](https://jen-hsuan-hsieh.gitbook.io/c-programming/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jen-hsuan-hsieh.gitbook.io/c-programming/1.4.multi-process-programming/1.3.1.using-mutex-to-prevent-reentry.md).

# Using Mutex to prevent reentry

* 為了防止設備或是process被重複開啟, 可以用Mutex鎖定設備或是process.&#x20;
* 當process結束或是主動釋放Mutex, 才可以讓其他process再度進入該程式碼中.
* 利用判斷Mutex來判斷設備或是process是否已被開啟也可以達到保護不被reentry.
* example: 鎖定特定的port:
  * 1.在開port時加入:

    ```
     char mutexName[20];
     sprintf(mutexName,"mutex%d",port);

     *hMutex = CreateMutexA(NULL, TRUE, mutexName);
     //printf("%d\n", *hMutex );
     if (*hMutex == NULL) {
       //printf("Error creating mutex.\n");
        return 0;
     }
     if (GetLastError() == ERROR_ALREADY_EXISTS) {
      //printf("The mutex alread exists.\n");
       return 0;
     }
    ```
  * 2.在關port時加入:

    ```
     ReleaseMutex(hMutex); 
     CloseHandle(hMutex);
    ```
