C - Linux - Pthreads 和信号量

标签 c linux multithreading pthreads semaphore

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

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 元素中)。然后,让老鼠在进入房间时等待信号量,并在离开房间时发布信号量。

关于C - Linux - Pthreads 和信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32876663/

相关文章:

C: char 中使用多个反斜杠

c++ - 在mysql服务器源代码中找不到 'ib_lock_t'的定义

c# - 在 C# 控制台应用程序中使用线程概念并行执行超过 2 个 Dtsx 包

Android Jni : crash in global and local ref variables

c# - 如何正确并行工作任务?

c - 有没有办法在 Windows 7 上以编程方式激活 Windows

c - Windows是否回收堆栈空间?

c++ - 为 C++ Linux 应用程序创建隐藏配置文件

java程序使操作系统难以格式化可移动磁盘

python - 找出磁盘空间差异的脚本