C - 无法将线程传递到具有特定票号的临界区

C - unable to pass thread into critical section with specific ticket number

我正在尝试实施 票证算法。我那里有 X 个线程,我想通过 票号 同步它们进入 临界区 ,票号为 0 的线程将进入临界区 first,数字 1 将作为 second 等输入

我在 while 循环中实现了这个关键部分问题,内部有 if 条件来检查线程票号。但我很想 避免使用主动等待 - 循环测试条件。

所以我在想是否还有其他方法可以使用包含条件的互斥锁,例如,线程被互斥锁锁定并等待某个全局变量具有与 thred 的票号相同的值。

这是我主动等待的功能:

void *threadInitial(void *void_ptr){

    // my thread structure with thread id and ticket number   
    Thread *threadActual = void_ptr;
    // get ticket number
    sem_wait(&semaphoreTicketGet);
    threadActual->threadTicket = getticket();
    sem_post(&semaphoreTicketGet);

    while(1){
      // check if this thread is allowed to enter critical section
      if(threadActual->threadTicket != enterTicketNumber)    continue;

      sem_wait(&semaphoreTicketPrint);
      // critical section
      enterTicketNumber++;
      sem_post(&semaphoreTicketPrint);
      break;
   }
   return NULL;
}

这个函数是这样调用的:

pthread_create(&threadsArr[count].threadPointer, NULL, threadInitial, &threadsArr[count])

你不知道怎么解决吗?

您可以使用条件变量:

"Condition variables provide yet another way for threads to synchronize. While mutexes implement synchronization by controlling thread access to data, condition variables allow threads to synchronize based upon the actual value of data."

https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

//global variable
pthread_cond_t      cond  = PTHREAD_COND_INITIALIZER;

void *threadInitial(void *void_ptr){

  // my thread structure with thread id and ticket number
  Thread *threadActual = void_ptr;

  // get ticket number
  sem_wait(&semaphoreTicketGet);
  threadActual->threadTicket = getticket();
  sem_post(&semaphoreTicketGet);

  // wait for my turn
  sem_wait(&semaphoreTicketPrint);
  while (threadActual->threadTicket != enterTicketNumber)
        pthread_cond_wait(&cond, &semaphoreTicketPrint);
  enterTicketNumber++;
  pthread_cond_signal(&cond);
  sem_post(&semaphoreTicketPrint);

  return NULL;

}