C - Linux - P线程和信号量

C - Linux - Pthreads and Semaphore

我在尝试使用 pthreads 实现信号量时遇到了问题。我尝试编写的场景是迷宫中的老鼠。老鼠是线,迷宫由相互连接的房间组成。老鼠必须穿过每个房间,每个房间都有不同的容量和等待时间,然后老鼠才能继续前进。我能够用一个 while 循环来实现它,让线程在等待一个点释放的同时等待并旋转,但我需要用信号量实现 objective 。这是我拥有的:

sem_t psem, csem;

void EnterRoom(int iRat, int iRoom) {

    time_t currentTime;

    currentTime = time(NULL);

    RoomVB[iRoom][iRat].tEntry = currentTime - startTime;
    RoomVB[iRoom][iRat].iRat = iRat;
    VisitorCount[iRoom]++;
    sleep(roomArray[iRoom].delay);
}

void LeaveRoom(int iRat, int iRoom) {

    time_t currentTime;

    currentTime = time(NULL);

    VisitorCount[iRoom]--;
    RoomVB[iRoom][iRat].tDep = currentTime - startTime;
}

void *rat(void *ratID) {

    if (sem_init(&csem, 0, 0) < 0) {
        perror("sem_init");
        exit(1);
    }

    int id;

    id = (int)ratID;

    int i;

    for (i = 0; i < numOfRooms; i++) {

    /*while (VisitorCount[i] >= roomArray[i].capacity) {

    }*/

    if (sem_init(&psem, 0, roomArray[i].capacity) < 0) {
        perror("sem_init");
        exit(1);
        }


    sem_wait(&psem);
    EnterRoom(id, i);
    sem_post(&csem);

    sem_wait(&csem);
    LeaveRoom(id, i);
    sem_post(&psem);

    }

    return NULL;

}

如您所见,我注释掉了 while 循环。我必须合并其他信息,例如老鼠穿过二维数组中的房间所需的时间。

错误结果:

Rat 0 completed maze in 5 seconds.
Rat 1 completed maze in 5 seconds.
Rat 2 completed maze in 5 seconds.
Room 0 [3 1]: 0 0 1; 1 0 1; 2 0 1; 
Room 1 [2 2]: 0 1 3; 1 1 3; 2 1 3; 
Room 2 [1 2]: 0 3 5; 1 3 5; 2 3 5; 
Total traversal time: 15 seconds, compared to ideal time: 15 seconds.

正确结果(通过循环实现):

Rat 0 completed maze in 7 seconds.
Rat 1 completed maze in 5 seconds.
Rat 2 completed maze in 9 seconds.
Room 0 [3 1]: 0 0 1; 1 0 1; 2 0 1; 
Room 1 [2 2]: 0 1 3; 1 1 3; 2 3 5; 
Room 2 [1 2]: 0 5 7; 1 3 5; 2 7 9; 
Total traversal time: 21 seconds, compared to ideal time: 15 seconds.

我假设我需要两个信号量,生产者信号量最初设置为 n - 这是每个房间的容量。我有什么想法可以修复它,使其正常工作吗?

您不能让每个线程同时重新初始化相同的两个共享信号量。在你的老鼠开始之前,信号量都需要预先初始化 运行。

解决这个问题的最简单方法是为每个房间设置一个信号量,初始化为该房间的容量(将信号量存储在该房间的 roomArray 元素中)。然后,让老鼠在进入房间时等待信号量,并在离开房间时 post 等待信号量。