Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Semaphores

Status
Not open for further replies.

CaptRage61

Programmer
Joined
Feb 17, 2005
Messages
50
Location
US
I am working on using semaphores to keep two threads from writing to the same variable but this is now working correctly, I beleive that the semaphore is created correctly can anyone tell if this is right:
Code:
int p(){
//sem is the sembuf struct
//x is the semid
  sem.sem_op = -1;
  semop(x, &sem, 1);
}

int v(){
  sem.sem_op = 1;
  semop(x, &sem, 1);
}


int producer()
{
   int i,in, local, sum = 0;
   printf(" Producer: writing %d items.\n", PRODUCER_REPS);

   i = 0;
   while (i < PRODUCER_REPS)
   {
      while (counter == BUFFER_SIZE) ;


      buffer[in] = ++i;
      in = (in + 1) % BUFFER_SIZE;

      // The next 4 lines implement a "slow" counter++;
      local = counter;
      local++;
      if (i == 10) work(100000);
      counter = local;

      p(); //this will force the consumer to wait till this
           //command is executed before it can update counter
           //and the buffer

      sum += i;
   }
   printf(" Producer done! Checksum was %d\n", sum);
}

int consumer()
{
   int i;
   int out;
   int sum = 0;
   printf("     Consumer: reading items.\n");

   i = 0;
   out = 0;
   while (i < PRODUCER_REPS)
   {
      while (counter == 0) ;

      v(); //waits for producer to update counter before
           //it can update counter and buffer

      i = buffer[out];
      out = (out + 1) % BUFFER_SIZE;

      counter--;

      sum += i;
   }
   printf("     Consumer checksum = %d\n",sum);
}
 
How exactly are you calling producer and consumer?



--
 
p = clone(producer, p_stackTop, CLONE_VM | SIGCHLD, NULL);
c = clone(consumer, c_stackTop, CLONE_VM | SIGCHLD, NULL);
 
I think you need to show the whole program

--
 
actually I think I just got it to work, thanks though
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top