操作系统实验

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <pthread.h>

#define MAX_BUFFER_SIZE 5
#define SHM_MODE 0600
#define SEM_MODE 0600
#define N 5

// Define your variables here
pthread_t philosophers[N]; // 哲学家线程
int forks[N];              // 哲学家叉子状态:1表示已被占用,0表示可用
pthread_mutex_t mutex;     // 互斥锁,用于保护临界区

// P Operation
void Wait(int sem_id, int sem_num)
{
    struct sembuf sb;
    sb.sem_num = sem_num;
    sb.sem_op = -1;
    sb.sem_flg = 0;
    semop(sem_id, &sb, 1);
}

// V Operation
void Signal(int sem_id, int sem_num)
{
    struct sembuf sb;
    sb.sem_num = sem_num;
    sb.sem_op = 1;
    sb.sem_flg = 0;
    semop(sem_id, &sb, 1);
}

void think(int i)
{
    printf("The philosopher of %d is thinking.\n", i);
    sleep(1);
}

void eat(int i)
{
    printf("The philosopher of %d is eating.\n", i);
    sleep(1);
}

void *philosopher(void *param)
{
    int i = *(int *)param;
    while (1)
    {
        think(i);
        // Take forks
        Wait(mutex, i);
        forks[i] = 1;
        forks[(i + 1) % N] = 1;
        Signal(mutex, i);
        // Eat
        eat(i);
        // Put forks
        Wait(mutex, i);
        forks[i] = 0;
        forks[(i + 1) % N] = 0;
        Signal(mutex, i);
        printf("The philosopher of %d has finished eating.\n", i);
    }
}

int main()
{
    // Initialize semaphores and shared memory
    int i;

    // 初始化叉子状态和互斥锁
    for (i = 0; i < N; i++)
    {
        forks[i] = 0;
    }
    pthread_mutex_init(&mutex, NULL);

    // 创建哲学家线程
    int philosopher_ids[N];
    for (i = 0; i < N; i++)
    {
        philosopher_ids[i] = i;
        pthread_create(&philosophers[i], NULL, philosopher, &philosopher_ids[i]);
    }

    // 等待哲学家线程结束
    for (i = 0; i < N; i++)
    {
        pthread_join(philosophers[i], NULL);
    }

    // 销毁互斥锁
    pthread_mutex_destroy(&mutex);

    printf("Parent Process is over!\n");
    fflush(stdout);
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值