⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 csharestr.cpp

📁 window下的多线程编程参考书。值得一读
💻 CPP
字号:
#include <stdio.h>
#include <tchar.h>
#include "CMcl.h"

#define MAX_STRING_SIZE     256
#define FILE_MAPPING_NAME   __TEXT("ShareStrSharedMemory")
#define MUTEX_NAME          __TEXT("ShareStrSharedMemoryMutex")
#define INITIAL_STRING      __TEXT("(nothing yet)")

int main( int argc, char *argv[]) {
    // create a named mutex and acquire it before we
    // create the shared memory region...
    // this allows us to synchronize the creation and
    // initialization of the shared memory region so that
    // the thread which initially creates the region is the thread
    // that initializes it...
    CMclMutex cMutex( FALSE, MUTEX_NAME);
    cMutex.Wait(INFINITE);

    // create a named region of shared memory...
    CMclSharedMemory cSharedMemory( MAX_STRING_SIZE, FILE_MAPPING_NAME);

    if (cSharedMemory.Status() == ERROR_ALREADY_EXISTS) {
        printf("Opened preexisting shared memory region.\n");
    }
    else if (cSharedMemory.Status() == NO_ERROR) {
        printf("Created shared memory region.\n");
    }
    else {
        printf("Unable to create shared memory region, exiting!\n");
        exit(-1);
    }

    // get a pointer to the shared memory region...
    LPTSTR lpSharedString = (LPTSTR) cSharedMemory.GetPtr();

    // initialize the string if necessary...
    if (cSharedMemory.IsCreator()) {
        _tcscpy( lpSharedString, INITIAL_STRING); 
    }

    // release the mutex...
    cMutex.Release();

    // local buffer for working with the shared memory...
    TCHAR szLocalString[MAX_STRING_SIZE];
    
    while (TRUE) {
        printf( "Type a string to share, [Enter] to display current string, or \"quit\":\n");
        
        // input string...
        _getts( szLocalString);
        
        if (_tcscmp( szLocalString, __TEXT("quit")) == 0) {
            // quit...
            break;
        }
        else if (szLocalString[0] == __TEXT('\0')) {
            // show the string...
            printf( "Current string is '%s'.\n", lpSharedString);
        }
        else {
            // set the string...
            _tcscpy( lpSharedString, szLocalString);
        }
    }

    // no need to clean up the shared memory region,
    // the CMclSharedMemory destructor will do it for us...

    // exit...
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -