在多个进程中加载​​ dll 的同一实例

发布于 2024-11-07 10:45:55 字数 348 浏览 2 评论 0原文

Lib1[dll]
{
class A
{
static int i=0;
}
}

Program1[exe] have reference to Lib1
{
 Class B
 {
    main()
    {
      A.i = 5;
    }
 }
}

Program2 [exe] have reference to Lib1
{
 Class C
 {
    main()
    {
      A.i = 5;
    }
 }
}

如果 Program1 和 Program2 同时执行,它们是否有可能引用 Lib1 的单个实例,并且对 Program1 中 Ai 的静态变量所做的更改可用于 Program2,反之亦然,

Lib1[dll]
{
class A
{
static int i=0;
}
}

Program1[exe] have reference to Lib1
{
 Class B
 {
    main()
    {
      A.i = 5;
    }
 }
}

Program2 [exe] have reference to Lib1
{
 Class C
 {
    main()
    {
      A.i = 5;
    }
 }
}

If Program1 and Program2 are executing simultaneously, is it possible that they reference to a single instance of Lib1 and change made to the static variable of A.i in Program1 are available to Program2 and viceversa,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧时浪漫 2024-11-14 10:45:55

一般来说,不,您所要求的东西是不可能或不推荐的。在大多数操作系统(Windows、Linux 等)中,每个程序实例都在与所有其他进程隔离的单独进程地址空间中运行。在某些情况下,共享 DLL 的只读可执行代码可以在进程之间共享,以减少总体内存消耗,但可写数据对于每个进程来说是本地的。

您可以通过利用操作系统服务显式设置可由多个进程访问的共享内存区域来实现您的要求。在 Windows 中,这可以通过创建命名共享内存对象,使用所有参与者事先知道的名称。然后,您可以将该内存块类型转换为结构类型,并在该内存区域中读取和写入字段,并且拥有该共享内存视图的所有进程都将看到相同的数据。

由于多个进程并发运行,因此还需要考虑共享内存区域中的数据如何更新。如果多个进程需要更新共享内存区域中的计数器字段或其他内容,那么您需要围绕该数据的读写实现线程安全实践,例如互锁增量或使用命名互斥对象作为独占访问锁。

In general, no, what you are asking for is not possible or recommended. In most operating systems (Windows, Linux, etc), each program instance runs in a separate process address space which is isolated from all other processes. In some cases, the read-only executable code of shared DLLs may be shared between processes to reduce overall memory consumption, but the writable data is local to each process.

You can achieve what you're asking for by making use of OS services to explicitly set up a shared memory area that can be accessed by multiple processes. In Windows, this can be done by creating named shared memory objects, using a name that is known in advance by all participants. You can then typecast that memory block to a structure type and read and write fields in that memory area, and all processes that have a view onto that shared memory will see the same data.

Since multiple processes are running concurrently, you will also need to think about how the data in the shared memory area is updated. If multiple processes need to update a counter field or whatnot in the shared memory area then you need to implement thread safe practices around read and write of that data, such as interlocked increment or using a named mutex object as an exclusive access lock.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文