Subject: inter process locking
To: None <netbsd-help@netbsd.org>
From: Feng Lu <Feng.Lu@mcs.vuw.ac.nz>
List: netbsd-help
Date: 10/26/2002 16:24:57
Hi,
I am using mutex for inter process locking. In the following code, I
expect that when a process is runing, its another instance should wait
until the previous instance completes. However, this does not work. why?
code
-----
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include </usr/pkg/include/pthread.h>
typedef struct {
pthread_mutex_t Interprocess_mutex;
int state;
}share_t;
share_t *share;
void readline(FILE *fp);
int main(int argc, char *args[]) {
pthread_mutexattr_t mattr;
int read_byte, i;
int shmid;
key_t key = 5347;
char *shm, *s;
//create a share memory
if((shmid = shmget(key, sizeof(share_t), IPC_CREAT|0666)) < 0) {
perror("shmget");
exit(1);
}
if((shm = shmat(shmid, NULL, 0)) == (char *)-1) {
perror("shamt");
exit(1);
}
share = (share_t *)shm;
if(share->state != 1 ) {
printf("init mutex\n");
share->state = 1;
pthread_mutexattr_init(&mattr);
pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&share->Interprocess_mutex, &mattr);
}
printf("state = %d\n", share->state);
pthread_mutex_lock(&share->Interprocess_mutex);
for(i = 0; i < 200000; i++) {
printf("%d\n", i);
}
pthread_mutex_unlock(&share->Interprocess_mutex);
shmdt((const void *)share);
exit(0);
}