有没有一种简单的方法可以将堆中的变量复制到共享内存中 [英] Is there an easy way to copy a variable in the heap into shared memory

查看:77
本文介绍了有没有一种简单的方法可以将堆中的变量复制到共享内存中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在堆上分配了两个带有指向彼此的指针的结构.我将多线程程序转换为多进程程序,因此必须将堆上的那些结构转换为共享内存.到目前为止,除了问题之外,我什么都没有遇到.我的助教建议我使用memcpy,但我不确定这是否会起作用.有什么方法可以将堆上的一组结构转换为共享内存?

I have a couple of structs with pointers to one another allocated on the heap. I'm converting a multi-threaded program to a multi-process program so I have to make those structs on the heap into shared memory. So far, I've run into nothing but problems on top of problems. MY TA suggested I use memcpy, but I'm not sure that's going to work. Is there any way to convert a set of structs on the heap into shared memory?

我正在使用的结构:

 struct SharedData {
    int da;
    int         isopen;
    int     refcount;   // reference count:  number of threads using this object
    unsigned int    front;      // subscript of front of queue
    unsigned int    count;      // number of chars in queue
    unsigned int    bufsize;
    pthread_cond_t buffer_full;
    pthread_cond_t buffer_empty;
    pthread_mutex_t mtex;
    fifo_t* queue;
    sem_t       empty_count;

    sem_t       full_count;
    sem_t       use_queue;  // mutual exclusion
};

struct OverSharedData{
    struct SharedData ** rep;
    int rop;
};

我稍后分配了OverSharedData ,SharedData结构和fifo_t队列,以及多个char 指针.是否都必须将它们都声明为共享内存?

I malloc'd OverSharedData , the SharedData structs, and the fifo_t queue, along with multiple char pointers later on. Do they all have to be declared as shared memory?

推荐答案

malloc()从堆中请求内存的方式中,有系统调用(例如shmget())来请求/创建共享内存段.如果请求成功,则可以在那复制任何内容. (是的,您可以使用memcpy.)但是请记住要注意指针,指针对于保存在其共享内存中的一个进程有效,不一定对使用该共享内存段的另一个进程有效.

In the way malloc() request memory from heap, there are system calls (for e.g. shmget()) to request/create shared memory segment. If your request is successful, you can copy whatever you like over there. (Yes, you can use memcpy.) But remember to be careful about pointers, a pointer valid for one process, kept in its shared memory, is not necessarily valid for another process using that shared memory segment.

所有读取和/或写入过程都可以访问共享内存.如果多个进程正在读取/写入共享内存段,那么不用说,需要应用某些同步技术(例如信号量).

The shared memory is accessible to all processes for reading and/or writing. If multiple processes are reading/writing to a shared memory segment, then, needless to say, some synchronization techniques (for e.g. semaphore) need to be applied.

请在共享内存上阅读.一个很好的来源是Michael Kerrisk的"Linux编程接口".

Please read up on shared memory. An excellent source is "The Linux Programming Interface" by Michael Kerrisk.

参考:

  • http://man7.org/linux/man-pages/man7/shm_overview.7.html
  • http://man7.org/linux/man-pages/man2/shmget.2.html
  • http://www.amazon.com/The-Linux-Programming-Interface-Handbook/dp/1593272200

这篇关于有没有一种简单的方法可以将堆中的变量复制到共享内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆