semaphores question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • EARNEST
    New Member
    • Feb 2010
    • 128

    semaphores question

    hey guys,
    let's say there is a while loop, that checks if it is allowed to write to a memory segment. if it is not allowed, it will wait a couple of ns, then it will check again and so on. what if semaphores unlock and let's say 2 processes at the same time will read it as unlocked and will try to perform action. how can i eliminate that?
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    One of them will get to the semaphore first, and will lock it. The other process will try to lock it but fail. The semaphore code is written so that the part that locks it is mutually exclusive (synchronized), requires some sort of resource so that it can't be done at the same time. This way, only the smallest amount of code possible is synchronized.

    If it is not working for you, the semaphore is not written correctly.

    Comment

    • EARNEST
      New Member
      • Feb 2010
      • 128

      #3
      Here is my semaphores, not sure abotu their correctness tho.
      Code:
      key_t sem_key;
      	sem_key = 2;
      
      	struct sembuf sbuf[1];
      	
      	union semun {
      		int val;
      		struct semid_ds *buf;
      		ushort * array;
      	} arg;
      
      	arg.val = 0;
      	
      	segm_id = semget(sem_key, 1, IPC_CREAT | 0666);
      	if (segm_id < 0)
      	{
      		perror("sem id, semget");
      		exit(1);
      	}
      	
      	if (semctl(segm_id, 0, SETVAL, arg) < 0)
      	{
      		//mvprintw(0,1,"cannot set");
      	}
      	else
      	{
      		//mvprintw(0,1,"initialized sems");
      	}
      	
      	sbuf[0].sem_num = 0;
      	sbuf[0].sem_op = 1;
      	sbuf[0].sem_flg = 0;
      
      /* DO IPC, SHARED MEM, WRITING or READINING */
      
      //when finished
      
      	sbuf[0].sem_num = 0;
      	sbuf[0].sem_op = -1;
      	sbuf[0].sem_flg = 0;

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Are these semaphore functions (semget and semctl) from a standard library or did you write them yourself?

        Comment

        • EARNEST
          New Member
          • Feb 2010
          • 128

          #5
          standard library, C, unix

          Comment

          Working...