c - 在c中的进程间同步中互斥体的使用

标签 c windows process synchronization mutex

我已经搜索了一段时间,但由于找不到正确的答案,所以决定询问。

实际上我有两个进程

流程1:

#include <windows.h>
#include <stdio.h>

// This process creates the mutex object.

int main(void)
{
    HANDLE hMutex; 

    hMutex = CreateMutex( 
        NULL,                        // default security descriptor
        TRUE,                       // mutex owned
        TEXT("AnotherMutex"));  // object name

    if (hMutex == NULL) 
        printf("CreateMutex error: %d\n", GetLastError() ); 
    else 
        if ( GetLastError() == ERROR_ALREADY_EXISTS ) 
            printf("CreateMutex opened an existing mutex\n"); 
        else printf("CreateMutex created a new mutex.\n");

    if(WaitForSingleObject(hMutex, INFINITE) == WAIT_FAILED)
        printf("Error while waiting for the mutex.\n");
    else
        printf("Mutex openned by second process.\n");

    CloseHandle(hMutex);

    return 0;
}

流程2:

#include <windows.h>
#include <stdio.h>

// This process opens a handle to a mutex created by another process.

int main(void)
{
    HANDLE hMutex; 

    hMutex = OpenMutex( 
        MUTEX_ALL_ACCESS,            // request full access
        FALSE,                       // handle not inheritable
        TEXT("AnotherMutex"));  // object name

    if (hMutex == NULL) 
        printf("OpenMutex error: %d\n", GetLastError() );
    else printf("OpenMutex successfully opened the mutex.\n");

    if(!ReleaseMutex(hMutex)){
        printf("Error while releasing the mutex.\n")
    }

    CloseHandle(hMutex);

    return 0;
}

因此,当我运行第一个进程时,它不会等待第二个进程释放互斥体,而是;由于互斥锁被创建为拥有的、无信号的,它不应该等到某个进程/线程释放它然后打印消息吗?

最佳答案

您似乎混淆了两种类型的同步对象:互斥体事件

互斥体通常用于保护对可共享资源的访问。在关键部分的入口处,应该调用 Mutex 上的 WaitForSingleObject。如果另一个执行单元(线程或进程)没有获得互斥锁,则该执行单元将获得它并继续运行,否则它将被锁定,直到其他进程释放它。在关键部分的末尾,应该释放互斥体。请参阅Using Mutexes 。这就是为什么您的进程没有被暂停。

另一方面,

事件用于同步执行单元或通知某些内容。当创建一个事件时,它会指定其信号状态。当调用 WaitForSingleObject 并且事件处于无信号状态时,执行单元将被挂起,直到有事件发出信号。请参阅Using Events

在您的情况下,您应该使用Event

关于c - 在c中的进程间同步中互斥体的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44162758/

相关文章:

c - 如何使用 fgets() 从 stdin 读取?

c - c编程中两个ASCII值的相加

windows - 在bat文件中运行bat文件

c# - Windows,启动服务 System.InvalidOperationException : Cannot start service on computer '.' Access in Denied(Running as Admin)

python - 如何使用 --passin 和 subprocess.Popen 自动化 Google App Engine upload_data?

父进程与多个子进程之间的通信

c - 为什么在生成随机 float 时会收到此错误?

objective-c - 我的程序中的输入语句被忽略

windows - 删除 Trailing\in subst 命令

php - ignore_user_abort 并在 php 中重定向?