아래는 printf
를 추가하여 choosing[]
및 ticket[]
배열의 값 변화를 출력하는 코드입니다. 이를 통해 각 스레드가 번호를 선택하고, 비교하며, 임계 구역을 실행하는 과정을 쉽게 확인할 수 있습니다.
📌 추가된 printf
출력 내용
- 번호 선택 과정 출력
"Thread X is choosing a number..."
→ 번호표를 선택하는 과정 표시."Thread X got ticket Y"
→ 할당된 번호표 확인.
- 임계 구역 진입 및 실행 과정 출력
"Thread X is entering the critical section."
→ 스레드가 임계 구역에 들어가는 순간 출력."Thread X is in the critical section."
→ 임계 구역에서 실행 중임을 표시.
- 임계 구역 종료 후 번호 반납
"Thread X is leaving the critical section."
→ 임계 구역을 빠져나가는 순간 표시.
📌 기대되는 실행 결과 예시
Thread 0 is choosing a number... Thread 0 got ticket 1 Thread 1 is choosing a number... Thread 1 got ticket 2 Thread 2 is choosing a number... Thread 2 got ticket 3 Thread 0 is entering the critical section. Thread 0 is in the critical section. Thread 0 is leaving the critical section. Thread 1 is entering the critical section. Thread 1 is in the critical section. Thread 1 is leaving the critical section. Thread 2 is entering the critical section. Thread 2 is in the critical section. Thread 2 is leaving the critical section.
이제 실행하면 각 프로세스의 번호표 선택 및 실행 과정이 보일 것입니다! 🚀
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #define NUM_THREADS 3 // 실행할 스레드 개수 int choosing[NUM_THREADS]; // 번호표를 선택하는 중인지 여부 int ticket[NUM_THREADS]; // 각 스레드의 번호표 void lock(int thread_id) { choosing[thread_id] = 1; printf("Thread %d is choosing a number...\n", thread_id); int max_ticket = 0; for (int i = 0; i < NUM_THREADS; i++) { if (ticket[i] > max_ticket) { max_ticket = ticket[i]; } } ticket[thread_id] = max_ticket + 1; choosing[thread_id] = 0; printf("Thread %d got ticket %d\n", thread_id, ticket[thread_id]); for (int i = 0; i < NUM_THREADS; i++) { if (i == thread_id) continue; while (choosing[i]); while (ticket[i] != 0 && (ticket[i] < ticket[thread_id] || (ticket[i] == ticket[thread_id] && i < thread_id))); } printf("Thread %d is entering the critical section.\n", thread_id); } void unlock(int thread_id) { ticket[thread_id] = 0; printf("Thread %d is leaving the critical section.\n", thread_id); } void *thread_function(void *arg) { int thread_id = *((int *)arg); lock(thread_id); printf("Thread %d is in the critical section.\n", thread_id); sleep(1); unlock(thread_id); return NULL; } int main() { pthread_t threads[NUM_THREADS]; int thread_ids[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { choosing[i] = 0; ticket[i] = 0; } for (int i = 0; i < NUM_THREADS; i++) { thread_ids[i] = i; pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]); } for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } return 0; }