问题
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