コード例 #1
0
ファイル: chopsticks.c プロジェクト: virtuahost/CS6210
/*
 * Uses pickup_left_chopstick and pickup_right_chopstick
 * to pick up the chopsticks
 */   
void pickup_chopsticks(int phil_id){
	if(phil_to_chopstick(phil_id, left) < phil_to_chopstick(phil_id, right))
    {
      pthread_mutex_lock(&chopstick_mutex[phil_to_chopstick(phil_id, left)]);
      pickup_left_chopstick(phil_id);
      pthread_mutex_lock(&chopstick_mutex[phil_to_chopstick(phil_id, right)]);
      pickup_right_chopstick(phil_id);
    }
    else
    {
      pthread_mutex_lock(&chopstick_mutex[phil_to_chopstick(phil_id, right)]);
      pickup_right_chopstick(phil_id);
      pthread_mutex_lock(&chopstick_mutex[phil_to_chopstick(phil_id, left)]);   
      pickup_left_chopstick(phil_id);  
    }
}
コード例 #2
0
ファイル: chopsticks.c プロジェクト: umichyiwan/gtthread
/*
 * Uses pickup_left_chopstick and pickup_right_chopstick
 * to pick up the chopsticks
 */   
void pickup_chopsticks(int phil_id){
    /* simple solution, always pick up the chopstick with lower number */
    int left_chopstick = (phil_id + 4) % 5;
    int right_chopstick = phil_id;
    if (left_chopstick < right_chopstick)
    {
        printf("Philosopher #%d tries to acquire left chopstick.\n", phil_id); 
        pthread_mutex_lock(&chopsticks[left_chopstick]);
        pickup_left_chopstick(phil_id);
        printf("Philosopher #%d tries to acquire right chopstick.\n", phil_id);  
        pthread_mutex_lock(&chopsticks[right_chopstick]);
        pickup_right_chopstick(phil_id);
    }
    else
    {
        printf("Philosopher #%d tries to acquire right chopstick.\n", phil_id);   
        pthread_mutex_lock(&chopsticks[right_chopstick]);
        pickup_right_chopstick(phil_id);
        printf("Philosopher #%d tries to acquire left chopstick.\n", phil_id);  
        pthread_mutex_lock(&chopsticks[left_chopstick]);
        pickup_left_chopstick(phil_id); 
    }
}