C++创建全局共享内存(官方例子)

Creating Named Shared Memory

Creating Named Shared Memory - Win32 apps | Microsoft Learn

Server:(First Process)

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

#define BUF_SIZE 256
TCHAR szName[]=TEXT("Global\\MyFileMappingObject");
TCHAR szMsg[]=TEXT("Message from first process.");

int _tmain()
{
   HANDLE hMapFile;
   LPCTSTR pBuf;

   hMapFile = CreateFileMapping(
                 INVALID_HANDLE_VALUE,    // use paging file
                 NULL,                    // default security
                 PAGE_READWRITE,          // read/write access
                 0,                       // maximum object size (high-order DWORD)
                 BUF_SIZE,                // maximum object size (low-order DWORD)
                 szName);                 // name of mapping object

   if (hMapFile == NULL)
   {
      _tprintf(TEXT("Could not create file mapping object (%d).\n"),
             GetLastError());
      return 1;
   }
   pBuf = (LPTSTR) MapViewOfFile(hMapFile,   // handle to map object
                        FILE_MAP_ALL_ACCESS, // read/write permission
                        0,
                        0,
                        BUF_SIZE);

   if (pBuf == NULL)
   {
      _tprintf(TEXT("Could not map view of file (%d).\n"),
             GetLastError());

       CloseHandle(hMapFile);

      return 1;
   }


   CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
    _getch();

   UnmapViewOfFile(pBuf);

   CloseHandle(hMapFile);

   return 0;
}

Client: (Second Process)

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")

#define BUF_SIZE 256
TCHAR szName[]=TEXT("Global\\MyFileMappingObject");

int _tmain()
{
   HANDLE hMapFile;
   LPCTSTR pBuf;

   hMapFile = OpenFileMapping(
                   FILE_MAP_ALL_ACCESS,   // read/write access
                   FALSE,                 // do not inherit the name
                   szName);               // name of mapping object

   if (hMapFile == NULL)
   {
      _tprintf(TEXT("Could not open file mapping object (%d).\n"),
             GetLastError());
      return 1;
   }

   pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
               FILE_MAP_ALL_ACCESS,  // read/write permission
               0,
               0,
               BUF_SIZE);

   if (pBuf == NULL)
   {
      _tprintf(TEXT("Could not map view of file (%d).\n"),
             GetLastError());

      CloseHandle(hMapFile);

      return 1;
   }

   MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);

   UnmapViewOfFile(pBuf);

   CloseHandle(hMapFile);

   return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++多线程编程中,如果需要多个线程共享变量,需要使用一些同步机制来保证数据的正确性。常用的同步机制包括互斥锁(mutex)、条件变量(condition variable)、信号量(semaphore)等等。 其中,互斥锁是最常用的同步机制之一。互斥锁可以保证同一时间只有一个线程可以访问被保护的变量,从而避免了竞争条件(race condition)的发生。当一个线程需要访问共享变量时,它必须先获得互斥锁,然后才能对变量进行操作。当这个线程完成操作后,必须释放互斥锁,以便其他线程可以访问变量。 下面是一个使用互斥锁共享变量的示例代码: ``` #include <iostream> #include <thread> #include <mutex> std::mutex mtx; // 全局互斥锁 int shared_var = 0; // 共享变量 void increment() { for (int i = 0; i < 1000000; i++) { std::lock_guard<std::mutex> lock(mtx); // 获得互斥锁 shared_var++; // 对共享变量进行操作 } } int main() { std::thread t1(increment); std::thread t2(increment); t1.join(); t2.join(); std::cout << "shared_var = " << shared_var << std::endl; return 0; } ``` 在上面的例子中,我们定义了一个全局互斥锁 `mtx` 和一个共享变量 `shared_var`。在 `increment` 函数中,我们使用 `std::lock_guard` 类来获得互斥锁,并对共享变量进行操作。在 `main` 函数中,我们创建两个线程来执行 `increment` 函数,并等待它们执行完毕。最后,我们输出共享变量的值。 需要注意的是,在多线程编程中,共享变量的操作可能会涉及到原子性问题,即一个操作可能被分为多个步骤,而这些步骤可能被其他线程中断。因此,在对共享变量进行读写操作时,需要保证这些操作是原子的,可以使用 C++11 中提供的原子操作来实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值