Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Hyung Jun Hahn
- #include <pthread.h>
- #include <time.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #define NUM_PERSON 5
- void think(int);
- void eat(int);
- void pickup_forks(int);
- void return_forks(int);
- void *person(void *count);
- pthread_mutex_t forks[NUM_PERSON];
- int main() {
- pthread_t tid[NUM_PERSON];
- pthread_attr_t attr;
- srand(time(NULL));
- int i;
- for (i = 0; i < NUM_PERSON; ++i) {
- pthread_mutex_init(&forks[i], NULL);
- pthread_attr_init(&attr);
- pthread_create(&tid[i], &attr, person, (void *) i);
- }
- for (i = 0; i < NUM_PERSON; ++i) {
- pthread_join(tid[i], NULL);
- }
- return 0;
- }
- void *person(void *count) {
- int* num = (int *)count;
- int temp = num;
- while (1) {
- think(temp);
- pickup_forks(temp);
- eat(temp);
- return_forks(temp);
- }
- }
- void think(int num) {
- // 1~3 seconds
- int time = (rand() % 3) + 1;
- printf("Person(%d) thinking for %d seconds\n", num, time);
- sleep(time);
- }
- void eat(int num) {
- // 1~3 seconds
- int time = (rand() % 3) + 1;
- printf("Person(%d) eating for %d seconds\n", num, time);
- sleep(time);
- }
- void pickup_forks(int num) {
- int left = (num + NUM_PERSON) % NUM_PERSON;
- int right = (num + 1) % NUM_PERSON;
- if (num == 1) {
- printf("Person(%d) waiting to pick up fork %d\n", num, right);
- pthread_mutex_lock(&forks[right]);
- printf("Person(%d) picked up fork %d\n", num, right);
- printf("Person(%d) waiting to pick up fork %d\n", num, left);
- pthread_mutex_lock(&forks[left]);
- printf("Person(%d) picked up fork %d\n", num, left);
- } else {
- printf("Person(%d) waiting to pick up fork %d\n", num, left);
- pthread_mutex_lock(&forks[left]);
- printf("Person(%d) picked up fork %d\n", num, left);
- printf("Person(%d) waiting to pick up fork %d\n", num, right);
- pthread_mutex_lock(&forks[right]);
- printf("Person(%d) picked up fork %d\n", num, right);
- }
- }
- void return_forks(int num) {
- printf("Person(%d) putting down forks\n", num);
- pthread_mutex_unlock(&forks[(num + 1) % NUM_PERSON]);
- pthread_mutex_unlock(&forks[(num + NUM_PERSON) % NUM_PERSON]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement