谁有没有什么共享内存的例子,简单一些也可以?只希望能提供一个参考!

解决方案 »

  1.   

    详见《Win32 多线程程序设计》第十三章(侯捷译)
    Multithreading Application in Win32 - The Complete Guide to Threads
    现把其中主要的读写部分的代码 Copy 你看看:
    //ShareMem.h
    ...
    struct SharedBlock;extern SharedBlock* gpSharedBlock;
    extern HANDLE       ghDataLock;struct SharedBlock
    {
        short   m_nStringCount;
        char __based( gpSharedBlock ) *m_pStrings[1];
    };
    ...//ShareDlg.cpp
    ...
    #include "ShareMem.h"
    ...
    void CShareMemDlg::OnWrite() 
    {
        // Make sure the shared memory is available
        ::WaitForSingleObject(ghDataLock, INFINITE);    CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT);
        ASSERT_VALID(pEdit);    int iLineCount = pEdit->GetLineCount();
        gpSharedBlock->m_nStringCount = iLineCount;
        char *pTextBuffer =
            (char *)gpSharedBlock
            + sizeof(SharedBlock)
            + sizeof(char __based(gpSharedBlock) *) * (iLineCount-1);    char szLineBuffer[256];
        while (iLineCount--)
        {
            // Get the next line from the edit control
            pEdit->GetLine(iLineCount, szLineBuffer, sizeof(szLineBuffer));        // Terminate it
            szLineBuffer[pEdit->LineLength(pEdit->LineIndex(iLineCount))] = '\0';        // Store the line in shared memory. The compiler
            // silently translates from a based pointer to
            // a regular pointer, so strcpy() works properly.
            strcpy(pTextBuffer, szLineBuffer);        // Remember where we put it. Convert to a based
            // ptr before storing the ptr.
            gpSharedBlock->m_pStrings[iLineCount] =
                (char _based(gpSharedBlock) *)pTextBuffer;        // Skip to the next open space in the buffer
            pTextBuffer += strlen(szLineBuffer) + 1;
        }    ::ReleaseMutex(ghDataLock);
    }void CShareMemDlg::OnRead() 
    {
        // Make sure the shared memory is available
        ::WaitForSingleObject(ghDataLock, INFINITE);    CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT);
        ASSERT_VALID(pEdit);
        pEdit->SetWindowText("");
        pEdit->SetSel(-1, -1);
        pEdit->ShowCaret();    for (int i=0; i<gpSharedBlock->m_nStringCount; i++)
        {
            CString str = gpSharedBlock->m_pStrings[i];
            str += "\r\n";
            pEdit->ReplaceSel(str);
        }    ::ReleaseMutex(ghDataLock);
    }