我们大家都知道,临界段代码只能在进程内同步。
现在有一个DLL,定义了共享数据段,这个共享数据段里有一个数据结构被各进程共享。
这个DLL被很多EXE调用。这个DLL导出一个函数:ModiValue,功能就是修改这个共享的数据结构,,,问题是:DLL被映射到了各个进程里去了,能否用临界段对这个共享数据结构实行同步?

解决方案 »

  1.   

    好像不太行;
    如果这种同步请考虑用Event或Mutex内核对象完成吧;
      

  2.   

    easy
    BOOL APIENTRY DllMain( HANDLE hModule, 
                           DWORD  ul_reason_for_call, 
                           LPVOID lpReserved
     )
    {
    switch( ul_reason_for_call ) 
    {
    case DLL_PROCESS_ATTACH:
    // Create a mutex with no initial owner.
    hMutex = CreateMutex( 
    NULL,                       // no security attributes
    FALSE,                      // initially not owned
    "MutexToProtectMMIStatus");  // name of mutex if (hMutex == NULL) 
    {
    //ERROR to create mutex
    MessageBox(NULL,"error to create mutex","Error",MB_OK);
    //exit
    return FALSE;
    }

    //One more dll refed
    g_s32DllRef ++;
    break;
    case DLL_PROCESS_DETACH:
    // close handle of the mutex
    CloseHandle(hMutex);
    //One dll nrefed
    g_s32DllRef --;
    break;
    default: break;
    }
    return TRUE;
    }
    STATUS GetMMIStatus(MMIStatus &mmiStatusStruRef)
    {
    //wait mutex
    if (WaitForMutex(hMutex) == OK)
    {
    //get the mutex
    //get MMI status
    memcpy(&mmiStatusStruRef,&g_mmiStatusStru,sizeof(MMIStatus));
    // dstatus = MMIStatues;
    //release mutex
    ReleaseMutex(hMutex);
    return OK;
    }
    else
    {
    //fail to get mutex
    return ERROR;
    }}
    STATUS WaitForMutex(HANDLE hMutex) 

        DWORD dwwaitresult;     // Request ownership of mutex.
    // wait the mutex for 5 second
        dwwaitresult = WaitForSingleObject( 
            hMutex,   // handle to mutex
            5000L);   // five-second time-out interval
     
        switch (dwwaitresult) 
        {
            // The thread got mutex ownership.
            case WAIT_OBJECT_0: 
    //get the mutex
    /*          __try 

                    // Write to the database.
                }             __finally

                    // Release ownership of the mutex object.
                    if (! ReleaseMutex(hMutex)) 

                        // Deal with error.
                    }       } 
    */ return OK;
    // break; 
      
            // Cannot get mutex ownership due to time-out.
            case WAIT_TIMEOUT: 
    //Faile to get mutex (reason is timeout)
    //            return FALSE;         // Got ownership of the abandoned mutex object.
            case WAIT_ABANDONED: 
    //Faile to get mutex(can not get)
    //            return FALSE; 
    default:break;//return FALSE;
        }//    return TRUE; 
    return ERROR;
    }
    ok了
      

  3.   

    总而言之,就是获取或修改共享数据段结构内容前先获取控制权mutex
      

  4.   

    sinhighly(非典型程序员):兄弟谢谢你,,,
    但是请你看清楚我的问题。