首页 > 解决方案 > 成对的屏障线程同步

问题描述

我想实现一个阻止传入线程的函数,直到 2 个相同颜色的线程相遇。每个线程都由唯一的 id 和颜色建模。该函数应返回与其匹配的另一个线程的 id。我尝试使用会合和屏障的想法来解决问题,当任何时候只有2个线程时它有效,但是当有2个以上的线程时,返回的id不正确。我试图先解决一种颜色,因为其他两种颜色会有类似的逻辑,但我不确定我需要改变什么?

 int pack_thread(int colour, int id) {
if (colour == 1) {
    sem_wait(&d); map[0][count[0]] = id; count[0]++; 
    if (count[0] == 1) {
        sem_post(&d);
        sem_post(&a1); sem_wait(&a2); sem_post(&barr);
        return map[0][1];
    } else if (count[0] == 2) {
        sem_post(&d);
        sem_wait(&a1); sem_post(&a2);
        return map[0][0];
    } else {
        sem_post(&d);
        sem_wait(&barr);
        map[0][1] = id; 
        count[0] = 0;
        sem_post(&a2);sem_wait(&a1);
        return map[0][0];
    }
} else {
    return 0;
}

标签: multithreadingoperating-systemsynchronizationsemaphore

解决方案


推荐阅读