Semaphores and shared memory

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 08:05:46

问题


I have a question regarding multiprocess programming in C, I have several reader processes that will be reading from a file into a shared buffer and several writer processes reading from the buffer and into another file, what type of semaphores will we need to use for this. and how can we use shared memory with the semaphores.


回答1:


If you're on linux, one easy option is to use pshared mutexes and condition variables. A recet version of glibc will be necessary. Essentially inside your shared memory segment you will have something like:

struct shmem_head {
    pthread_mutex_t mutex;
};

To initialize:

void init_shmem_head(struct shmem_head *head)
{
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED );

    pthread_mutex_init(&head->mutex, &attr);
    pthread_mutexattr_destroy(&head->mutex);
}

You now have a mutex, shared by all processes with the shared memory segment open. You can simply use pthread_mutex_lock to lock and pthread_mutex_unlock to unlock as normal. There's also a similar pthread_condattr_setpshared if you want condition variables as well.



来源:https://stackoverflow.com/questions/6414160/semaphores-and-shared-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!