Subject: Re: inter process locking
To: Feng Lu <Feng.Lu@mcs.vuw.ac.nz>
From: Pramod Srinivasan <pramod@redback.com>
List: netbsd-help
Date: 10/25/2002 20:46:38
Feng,
Which version of netbsd do you use? I remeber vaguely that ipl did not
work for me as I was using an older version of netbsd. I think I was using
a 1.4.2 netbsd, but when I tried the same on 1.5.x, it worked fine.
--pramod
On Sat, 26 Oct 2002, Feng Lu wrote:
> Date: Sat, 26 Oct 2002 16:24:57 +1300 (NZDT)
> From: Feng Lu <Feng.Lu@mcs.vuw.ac.nz>
> To: netbsd-help@netbsd.org
> Subject: inter process locking
>
> 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);
>
> }
>
>
----------------------------------------------------------------------
Pramod Srinivasan,
Software Engineer, Redback Networks
350 Holger way,San Jose, CA 95134-1362
PH - 408-750-8537 (O) 408-988-8475 (H)
-----------------------------------------------------------------------