I have a homework project that require the creation of a STATIC library to provide mutual access to a couple of named pipes.
These pipes are used for communication between various clients using the library and a server.
Now, suppose I want to use pthread mutexes; how can I achieve that? How can the processes know which is the shared memory area in which the mutex is stored? And who should require this memory area? The server can’t because it’s required the library itself to provide mutual exclusion.
Thanks to asveikau i came up with this:
#define SHARED 1
#define MUTEX 1
int main() {
sem_t* mutex = sem_open("mutex", O_CREAT);
sem_init(mutex, SHARED, MUTEX);
fork(), fork(), fork();
sem_wait(mutex);
int i;
for(i = 0; i < 10; i++)
printf("process %d %d\n", getpid(), i), fflush(stdout);
sem_post(mutex);
}
that from the output really seem to solve my problem.
Thank you to everyone.
I put this down as a comment, but it’s worth an answer I think.
As others state, pthread mutexes are not cross-process. What you need is a “named mutex”. You can use
sem_opento create a cross-process semaphore, and give it an initial count of 1. In that casesem_waitbecomes “mutex lock” andsem_postbecomes “mutex unlock”.Note that
sem_open, while part of POSIX, is not universally supported. I believe it works on Linux and Mac OS X. Probably Solaris if you care about that (these days you probably don’t). I know on OpenBSD it always fails withENOSYS. YMMV.