哲学家进餐问题的mutex解法

筷子的数据结构

typedef struct chopstick {
  pthread_mutex_t mtx;
  char* whoami;
} chopstick_t;


chopstick_t* chopstick_get(char const* const str) {
  if ( str == NULL ) {
    perror("Please Pass A Name Of Chopstick.");
  }
  chopstick_t* tmp = NULL;
  if( (tmp = calloc(1,sizeof(chopstick_t))) == NULL) {
    return NULL;
  }
  chopstick_init(tmp, str);
  return tmp;
}

int chopstick_init(chopstick_t* cs, char const*const str) {
  if( !(cs && str) ) {
	  return -1;
  }
  return (cs->whoami = strdup(str)) && !(pthread_mutex_init(&(cs->mtx), NULL));
}

int chopstick_destory(chopstick_t** cs) {
  if( *cs != NULL ) {
    free(*cs);
    *cs = NULL;
    return 0;
  }
}

哲学家的数据结构


typedef struct philolosopher_ {
  chopstick_t* lcs;
  chopstick_t* rcs;
  char const* whoami;
} philolosopher_t;

philolosopher_t* philolosopher_get(char const*const str) {
    if ( str == NULL ) {
    perror("Please Pass A Name Of Chopstick.");
  }
  chopstick_t* tmp = NULL;
  if( (tmp = calloc(1,sizeof(philolosopher_t))) == NULL) {
    return NULL;
  }
  philolosopher_init(tmp, str);
  return tmp;
}

int philolosopher_init(philolosopher_t* phil, char const*const str) {
  if( !(phil && str) ) {
	  return -1;
  }
  phil->lcs = NULL;
  phil->rcs = NULL;
  return (phil->whoami = strdup(str));
}

int philolosopher_chopstick_init(philolosopher_t* phil, chopstick_t* lcs, chopstick_t* rcs) {
  return (phil->lcs = lcs) && (phil->rcs = rcs);
}

int philolosopher_destory(philolosopher_t** phil) {
  if (*phil != NULL) {
    free(*phil);
    *phil = NULL;
    return 0;
  }
  return -1;
}

void philolosopher_eating(philolosopher_t* phil) {
  pthread_mutex_lock(&phil->lcs->mtx); //----> 1
  pthread_mutex_lock(&phil->rcs->mtx);
  printf("Im %s, Im eating...\n", phil->whoami);
  sleep(rand()%3);
  pthread_mutex_unlock(&phil->rcs->mtx);
  pthread_mutex_unlock(&phil->lcs->mtx);
  printf("Im %s, Im eating over...\n", phil->whoami);
}

void philolosopher_thinking(philolosopher_t* phil) {
  printf("Im %s, Im thinking...\n", phil->whoami);
  sleep(rand()%3);
}

void* philolosopher_live(void *args) {
  philolosopher_t* phil = (philolosopher_t*)args;
  while(1) {
    if( (rand() % 2) == 1) {
      philolosopher_eating(phil);
    } else {
      philolosopher_thinking(phil);
    }
  }
  return ;
}

在1处使用了所有哲学家按照从左到右来获取筷子,必须先拿到左边的筷子,才能拿到右边的筷子。这样还是会发生死锁。其获得各个获得筷子的哲学家应该是如图所示:
哲学家进餐问题的mutex解法_数据结构
这种出现的原因是,并没有对两个筷子进行保护导致的。