printf("ho_tari\n");

Chapter 18 (semaphore, thread) 본문

TCP IP 소켓 프로그래밍

Chapter 18 (semaphore, thread)

호타리 2023. 10. 11. 16:29

<thread1.c>

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>

void* thread_main1(void *arg);
void* thread_main2(void *arg);
void* thread_main3(void *arg);

static sem_t sem_one;
static sem_t sem_two;
static sem_t sem_three;

int main(int argc, char *argv[]) 
{
   pthread_t t1_id, t2_id, t3_id;
   int thread_param=5;

   sem_init(&sem_one, 0, 0);
   sem_init(&sem_two, 0, 0);
   sem_init(&sem_three, 0, 1);
   
   pthread_create(&t1_id, NULL, thread_main1, (void*)&thread_param);
   pthread_create(&t2_id, NULL, thread_main2, (void*)&thread_param);
   pthread_create(&t3_id, NULL, thread_main3, (void*)&thread_param);

   pthread_join(t1_id,NULL);
   pthread_join(t2_id,NULL);
   pthread_join(t3_id,NULL);

   sleep(10); puts("end of main");

   sem_destroy(&sem_one);
   sem_destroy(&sem_two);
   sem_destroy(&sem_three);

   return 0;
}

void* thread_main1(void *arg) 
{
   int i;
   int cnt=*((int*)arg);
   for(i=0; i<cnt; i++)
   {
	  sleep(1);
	  sem_wait(&sem_one);
      puts("running thread1");
	  sem_post(&sem_three);  
   }
   return NULL;
}

void* thread_main2(void *arg) 
{
   int i;
   int cnt=*((int*)arg);
   for(i=0; i<cnt; i++)
   {
	  sleep(1);  
	  sem_wait(&sem_two);
      puts("running thread2");
	  sem_post(&sem_one);    
   }
   return NULL;
}

void* thread_main3(void *arg) 
{
   int i;
   int cnt=*((int*)arg);
   for(i=0; i<cnt; i++)
   {
	  sleep(1);  
	  sem_wait(&sem_three);
      puts("running thread3");
	  sem_post(&sem_two);    
   }

   return NULL;
}

 

<compile 결과>

 

thread1을 먼저 시작하고 1, 2, 3 순으로 출력하려면 sem_init값을 1이 먼저 시작해야하므로 thread1만 1로 나머지는 0으로 설정하고 각 thread_main 함수들에서 sem_wait과 sem_post를 1, 2, 3 순으로 무한반복이 될 수 있게 설정한다.

thread2를 먼저 시작하고 2, 1, 3 순으로 출력하려면 sem_init값을 2가 먼저 시작해야하므로 thread2만 1로 나머지는 0으로 설정하고 각 thread_main 함수들에서 sem_wait과 sem_post를 2, 1, 3 순으로 무한반복이 될 수 있게 설정한다.

 

'TCP IP 소켓 프로그래밍' 카테고리의 다른 글

Chapter 18 (semaphore)  (0) 2023.10.11
Chapter 18 (thread, mutex)  (0) 2023.10.11
Chapter 9 (get, set)  (0) 2023.10.11
Chapter 8 (gethostbyname, gethostbyaddr)  (0) 2023.10.11
Chapter 5 (echo_client2)  (0) 2023.10.11