简体   繁体   English

矩阵乘法中的共享内存涉及多个进程

[英]Shared memory in matrix multiply involving multiple processes

I am trying to learn IPC via shared memory . 我正在尝试通过共享内存学习IPC。 I don't understand one thing how do I allocate shared memory to various variables of different processes.For example , in a matrix multiplication i don't want to declare matrix globally but via shared memory . 我不了解如何为不同进程的各个变量分配共享内存。例如,在矩阵乘法中,我不想全局声明矩阵,而是通过共享内存声明。 How do we attach memory to different matrices as : 我们如何将内存附加到不同的矩阵上,如:

Could anyone help me with this ? 有人可以帮我吗? Also , can it be replaced by mmap() and shm_open() or is it just files ? 另外,可以将其替换为mmap()和shm_open()还是仅仅是文件? If yes , how ? 如果是,怎么办? I could not find apt examples in which how shared memory is modified by the processes is illustrated . 我找不到合适的示例来说明如何通过进程修改共享内存。

First of all: Don't use shared memory for IPC. 首先:不要将共享内存用于IPC。 It's messy. 太乱了

In most situations where shared memory would make sense, it's easier and more appropriate to just use threads (so that all memory is shared). 在共享内存有意义的大多数情况下,仅使用线程(这样便可以共享所有内存)更容易,也更合适。 When that isn't possible, you're probably better off using some sort of message-passing scheme. 如果不可能,那么最好使用某种消息传递方案。

How do I allocate memory from this shared memory for matrix A , B and resultant matrix and 如何从此共享内存为矩阵A,B和结果矩阵分配内存,以及
attach to it as I don't have to declare matrices globally and each process would need ABC to do 附加到它,因为我不必全局声明矩阵,每个过程都需要ABC来做
part of problem. 问题的一部分。

You'd have to come up with some way to allocate memory within the shared memory segment. 您必须想出一些方法在共享内存段中分配内存。 You can't use malloc() for this, since its arena doesn't include the shared memory. 您不能为此使用malloc() ,因为它的竞技场不包含共享内存。

If the only data you're going to store is going to be those three matrices, and the size of those matrices is known to both processes, you could just stack them all into a structure and store that in the segment: 如果要存储的唯一数据是这三个矩阵, 并且两个进程都知道这些矩阵的大小,则可以将它们全部堆叠到一个结构中并将其存储在段中:

struct shm_data {
    float A[123][123], B[123][123], C[123][123];
};

struct shm_data *mat = (struct shm_data *) shm;

If the size of the matrices isn't fixed, though, you'd have to figure their addresses at runtime. 但是,如果矩阵的大小不固定,则必须在运行时计算它们的地址。

Also , can it be replaced by mmap() and shm_open() or is it just files ? 另外,可以将其替换为mmap()和shm_open()还是仅仅是文件?

Yes. 是。 In fact, mmap() is almost universally preferable to shm_open() , as the memory segment is backed by a file and obeys filesystem semantics, so it can be cleaned up sensibly. 实际上, mmap()几乎普遍优于shm_open() ,因为内存段由文件支持并且遵循文件系统语义,因此可以合理地对其进行清理。 POSIX shared memory (which is what you're using) is much weirder. POSIX共享内存(您正在使用的内存)非常奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM