#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
int x = 0;
int y = 0;
pthread_mutex_t lock1;
pthread_mutex_t lock2;
void* worker1(void* arg) {
pthread_mutex_lock(&lock1);
printf("%s lock1 μ κΈ\n", (char*)arg);
x++;
sleep(2);
pthread_mutex_lock(&lock2);
printf("%s lock2 μ κΈ\n", (char*)arg);
y++;
pthread_mutex_unlock(&lock2);
printf("%s lock2 ν΄μ \n", (char*)arg);
pthread_mutex_unlock(&lock1);
printf("%s lock1 ν΄μ \n", (char*)arg);
}
void* worker2(void* arg) {
pthread_mutex_lock(&lock2);
printf("%s lock2 μ κΈ\n", (char*)arg);
y++;
sleep(2);
pthread_mutex_lock(&lock1);
printf("%s lock1 μ κΈ\n", (char*)arg);
x++;
pthread_mutex_unlock(&lock1);
printf("%s lock1 ν΄μ \n", (char*)arg);
pthread_mutex_unlock(&lock2);
printf("%s lock2 ν΄μ \n", (char*)arg);
}
int main() {
char *name[] = {"ν©κΈ°ν","μ΄μ°¬μ"};
pthread_t tid[2];
pthread_mutex_init(&lock1, NULL);
pthread_mutex_init(&lock2, NULL);
pthread_create(&tid[0], NULL, worker1, name[0]);
pthread_create(&tid[1], NULL, worker2, name[1]);
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock2);
pthread_mutex_destroy(&lock1);
printf("x = %d, y = %d\n", x, y);
return 0;
}