c语言中interforcess同步中互斥量的使用

c语言中interforcess同步中互斥量的使用,c,windows,process,synchronization,mutex,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, // defaul

我已经搜索了一段时间,我决定问,因为我找不到正确的答案

实际上我有两个过程

过程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;
}
#包括
#包括
//此过程将创建互斥对象。
内部主(空)
{
处理hMutex;
hMutex=创建互斥对象(
NULL,//默认安全描述符
TRUE,//拥有互斥锁
TEXT(“AnotherMutex”);//对象名称
if(hMutex==NULL)
printf(“CreateMutex错误:%d\n”,GetLastError());
其他的
如果(GetLastError()==错误\u已存在)
printf(“CreateMutex打开了一个现有的互斥\n”);
else printf(“CreateMutex创建了一个新的互斥。\n”);
if(WaitForSingleObject(hMutex,无限)=等待\u失败)
printf(“等待互斥时出错。\n”);
其他的
printf(“第二个进程打开的互斥锁。\n”);
密柄(hMutex);
返回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;
}
#包括
#包括
//此进程打开另一进程创建的互斥锁的句柄。
内部主(空)
{
处理hMutex;
hMutex=OpenMutex(
互斥对象\u所有\u访问,//请求完全访问
FALSE,//句柄不可继承
TEXT(“AnotherMutex”);//对象名称
if(hMutex==NULL)
printf(“OpenMutex错误:%d\n”,GetLastError());
else printf(“OpenMutex成功打开互斥锁。\n”);
如果(!ReleaseMutex(hMutex)){
printf(“释放互斥锁时出错。\n”)
}
密柄(hMutex);
返回0;
}

因此,当我运行第一个进程时,它不会等待第二个进程释放互斥锁,而是;由于互斥体是创建的、拥有的、未签名的,所以它不应该等到某个进程/线程释放它后再打印消息?

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

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

另一方面,
事件
用于同步执行单元或通知某些内容。当创建事件时,它指定其信号状态。当调用
WaitForSingleObject
且事件处于无信号状态时,执行单元将暂停,直到有东西向事件发出信号。看


底线在您的情况下,您应该在等待已拥有的互斥锁的第一个过程中使用
事件

,以便立即满足等待;在第二个过程中,您将释放一个您不拥有的互斥锁,这是非法的。我认为尤金是对的,你应该用事件来代替。