哲学家吃饭

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

struct chops{
    int id;
    pthread_mutex_t *left, *right;
};

void *philosopher(void * arg)
{
    struct chops * p = arg;
    while(1){
        pthread_mutex_lock(p->left);
        printf("%d:left\n",p->id);

        pthread_mutex_lock(p->right);
        printf("%d:right\n",p->id);

        pthread_mutex_unlock(p->right);
        pthread_mutex_unlock(p->left);
        printf("%d:unlock\n",p->id);
    }
}
#define PMI PTHREAD_MUTEX_INITIALIZER
int main(void)
{
    pthread_t id[5];
    pthread_mutex_t mutex[5]={PMI,PMI,PMI,PMI,PMI};
    struct chops chops[5];
    int i;
    for(i=0;i<5;i++){
        chops[i].id = i;
        chops[i].left = &mutex[i];
        chops[i].right= &mutex[(i+1)%5];
        pthread_create(&id[i] , NULL 
                       , philosopher, &chops[i]);
    }
	pthread_join(id[0],NULL);

	return 0;
}                                                                


你可能感兴趣的:(哲学家吃饭)