Reputation: 1373
I am currently trying to sinchronize two processess in Linux using the pthread_mutex model.
Here's the code I am working on:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
using namespace std;
int main (int argc, char **argv)
{
printf ("starting process\n");
if (_POSIX_THREAD_PROCESS_SHARED == -1) {
printf ("shared mutex is not supported!\r\n");
}
pthread_mutexattr_t attr;
pthread_mutex_t shm_mutex;
if (pthread_mutexattr_init(&attr) != 0)
printf ("init attr error!\r\n");
if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL) != 0)
printf ("set type error!\r\n");
if (pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED) != 0)
printf ("set shared error!\r\n");
int value;
if (pthread_mutexattr_getpshared(&attr, &value) != 0 || value != PTHREAD_PROCESS_SHARED) {
printf ("mutex is not shared!\r\n");
}
if (pthread_mutex_init(&shm_mutex, &attr) != 0)
printf ("mutex init error!\r\n");
for (int i=0; i < 10; i++) {
if (pthread_mutex_lock(&shm_mutex) != 0)
printf ("lock error!\r\n");
printf ("begin run %d\r\n", i);
sleep(10);
printf ("end run %d\r\n", i);
if (pthread_mutex_unlock(&shm_mutex) != 0)
printf ("unlock error!\r\n");
sleep(1); // sleep 1 second
}
pthread_mutex_destroy(&shm_mutex);
pthread_mutexattr_destroy(&attr);
return 0;
}
When I run two separate processes, the begin/end logic doesm't work.
Is there anything wrong with the code?
Upvotes: 1
Views: 182
Reputation: 1199
You're supposed to allocate shm_mutex
in shared memory yourself. See man shm_overview
. The flag merely means you're allowed to do this with the mutex.
See this reference for more detailed information.
Upvotes: 3