Pthread cond поддерживает второй элемент в очереди - PullRequest
0 голосов
/ 30 апреля 2020

Я пытаюсь реализовать программу синхронизации pthread. Существует очередь, в которой ожидают потоки, а потребительский поток извлекает элемент и отправляет сигнал, чтобы он продолжал работать. Моя реализация очереди работает правильно.

    void *landing_func(void* ID)
{   
    int plane_id = (int)ID;
    Plane plane;
    // init plane


    pthread_mutex_lock(&runway_mutex);
    if(emergency_check)
        enqueue(emergency, plane);
    else
        enqueue(landing, plane);

    if(plane_id == 1) // signal the controller thread to start popping
        pthread_cond_signal(&runway_cond);
    pthread_mutex_unlock(&runway_mutex);

    pthread_cond_timedwait(&all_planes[plane_id].cond, &(all_planes[plane_id].lock), &ts);
    // log the plane information
    pthread_mutex_unlock(&(all_planes[plane_id].lock));
    pthread_exit(NULL);
};


void *air_control()
{   
    pthread_cond_wait(&runway_cond, &start_mutex); // wait for the first plane to come
    int id, waiting;
    time_t current_time = time(NULL);
    while(current_time < end_time)
    {   
        pthread_mutex_lock(&runway_mutex);
        waiting = (departing->size > 0) ? (int)(current_time - top(departing).arrival_time) : 0;
        if(emergency->size > 0){
            id = dequeue(emergency);
        } else {
            if((landing->size > 0 && waiting < 10 && departing->size < 5) || (landing->size > 10)){
                id = dequeue(landing);
            } else if(landing->size == 0 && departing->size > 0){
                id = dequeue(departing);
            } else if((departing->size > 0 && waiting >= 10) || (departing->size > 0 && departing->size >= 5)){
                id = dequeue(departing);
            }
        }

        pthread_cond_signal(&(all_planes[id].cond)); // signal a thread in the related queue
        pthread_mutex_unlock(&runway_mutex);
        pthread_sleep(2 * t);
        current_time = time(NULL);
    }
    pthread_mutex_unlock(&start_mutex);
    pthread_exit(NULL);
};

Существует также очередь отправления и функция отправления, которая аналогична посадке. Плоскость с id = 1 является вылетающей плоскостью. Однако, когда я регистрирую информацию о самолетах, самолет с идентификатором 3 приходит перед самолетом с идентификатором 2, они оба посадка потоки.

Я не могу понять, почему 3 предшествует 2. Может кто-нибудь помочь мне разобраться?

struct Plane has a lock and cond inside. 
Plane all_planes[MAX_PLANES]
...