是的,這應該用票鎖來完成。 https://en.wikipedia.org/wiki/Ticket_lock
一個例子可能看起來像
int current_waiting_thread_ticket = 0;
int max_waiting_thread_ticket = 0;
pthread_mutex_t mutex; //initialize somewhere
pthread_cond_t cond; //initialize somewhere
void lock() {
int local_ticket;
pthread_mutex_lock(&mutex);
// get current ticket
local_ticket = max_waiting_thread_ticket;
// set next ticket
max_waiting_thread_ticket++;
// wait until the local ticket is ready
while (current_waiting_thread_ticket != local_ticket) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
void unlock() {
pthread_mutex_lock(&mutex);
// next ticket is ready
current_waiting_thread_ticket++;
// wake up all waiting threads
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}