Automotive Software

pthread_attr_t 를 이용한 쓰레드 detached 로 생성하기 예제 본문

포직스 (POSIX)/쓰레드 프로그램 예제 (Thread Program Example)

pthread_attr_t 를 이용한 쓰레드 detached 로 생성하기 예제

AutoSW 2020. 9. 24. 22:56
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

/* user defined macro */
#define COUNT_INIT_VALUE 0x00
#define COUNT_DUMMY_VALUE 0xA0

pthread_once_t InitOnce = PTHREAD_ONCE_INIT; /* it needs to be initialized as PTHREAD_ONCE_INIT */
int ClientCount = COUNT_DUMMY_VALUE;

void init_ClientCount( void )
{
  printf("ClientCount(), Before : ClientCount = %d\n", ((COUNT_DUMMY_VALUE == ClientCount)? COUNT_DUMMY_VALUE : ClientCount));
  ClientCount = COUNT_INIT_VALUE; /* user defined macro */
  printf("ClientCount(), After : ClientCount = %d\n", ClientCount);
}

void *client_Thread( void *arg )
{
  /* check and init. once, if it is not initialized */
  (void)pthread_once( &InitOnce, init_ClientCount ); /* return vlaue is ignored, since the once-object is initialized */

  /* increment the counter */
  ClientCount += 1;

  printf("client_Thread(), The number of clients : %d\n", ClientCount);

  while(1)
  {
      /* dummy */
  }

  return arg;
}

int create_detachedThread( pthread_t *pThreadId )
{
    int retVal;
    int result = 1;
    pthread_attr_t threadAttr;

    /* init. first before it is used */
    retVal = pthread_attr_init(&threadAttr);
    if( retVal != 0 )
    {
        printf("create_detachedThread(), Failed with pthread_attr_init()");
        abort();
    }
    else
    {
        /* set the attribute with PTHREAD_CREATE_DETACHED by calling according function */
        retVal = pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
        if( retVal != 0 )
        {
            printf("create_detachedThread(), Failed with pthread_attr_setdetachstate()");
            abort();            
        }
        else
        {
            /* create a Thread */
            retVal = pthread_create(pThreadId, &threadAttr, client_Thread, NULL);
            if( retVal != 0 )
            {
                printf("create_detachedThread(), Failed with pthread_create()");
                abort();                            
            }
            else
            {
                /* went through the procedure, succeeded */
                result = 0;
            }
        }
    }

    return result;
}

void run_Thread( void )
{
    pthread_t threadId;
    void *threadRet;
    int retVal;

    retVal = create_detachedThread(&threadId);
    if( retVal != 0 )
    {
        printf("run_Thread(), Failed with create_detachedThread()");
        abort();
    }
    else
    {
        printf("run_Thread(), Thread ID : %ld as detached is created\n", threadId);
        /* further handling e.g., pthread_join() is not required required anymore */
    }
}

int main( void )
{
    char inputCh;
    printf("Enter your command (t->Thread, q->quit): ");

    while(1)
    {
        if( scanf("%c", &inputCh) )
        {
            switch(inputCh)
            {
                case 'q':
                {
                    printf("Bye : Exit this program\n");
                    exit(EXIT_SUCCESS);
                    break;
                }
                case 't':
                {
                    printf("Run the Thread\n");
                    run_Thread();
                    break;
                }
                case 0x0a:
                {
                    /* enter */
                    break;
                }
                default : 
                {
                    printf("Try again : ");
                    break;
                }
            }
        }
    }

    pthread_exit(NULL); /* the process will terminate when the last thread exits */

    return 0;
}

테스트 결과 : 다음의 예제와 동일한 결과를 나타냄 (autosw.tistory.com/8?category=932055)

생성된 Thread 확인, ps -T -p PID

 TIP! 메인 쓰레드 종료 시, pthread_exit()를 호출하며 최종 쓰레드가 종료되길 기다림
 

pthread_once()를 이용한 쓰레드 공유 변수 한번만 초기화 하기 예제

#include #include #include /* user defined macro */ #define COUNT_INIT_VALUE 0x00 #define COUNT_DUMMY_VALUE 0xA0 pthread_once_t InitOnce = PTHREAD_ONCE_INIT; /* it needs to be initialized as PTHREAD..

autosw.tistory.com