프로그래밍2008. 4. 28. 21:08
반응형


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

void *
thread_function(void *arg);

int main(int argc, char **argv)
{
   
int state;
   
pthread_t t_id; //생성된 threadid저장공간
   
state = pthread_create(&t_id, NULL, t

                hread_function, NULL);

    //쓰레드 생성
    if(state != 0
) //error 일 시
    {
        puts("Thread creation error~!\n");
        exit(1);
   
}

    sleep(3);
    puts("main function is end");
    return 0;
}
 

 

void *thread_function(void *arg) //실행 함수

{
   
int i;
    for(
i=0; i<3; i++){
        sleep(2);
        puts("Thread is running..");}
}


=====================================================================

실행화면

사용자 삽입 이미지

위의 소스 예제는

pthread_create함수만을 이용해서 thread를 생성시킨 예제이다.

실행화면을 보면

thread_running 이라는 문구가 한번만 출력된 것을 볼  수 있다.

소스과정에는 for문을 이용해 3번을 출력하도록 되어있는데.........

왜 이런 결과값이 나온것일까??


자..그럼 두번째 소스코드와 실행화면을 보도록 하자..


 

#include <stdio.h>
#include <
unistd.h>
#include <
stdlib.h>
#include <
pthread.h>
#include <
string.h>

void *
thread_function(void *arg);

int main(int argc, char **argv)
{
   
int state;
   
pthread_t t_id;//생성된 threadid저장공간
    void *
t_return;
   
state = pthread_create(&t_id, NULL, t

                hread_function, NULL);

    //쓰레드 생성
    if(state != 0)
    {
        puts("Thread creation error~!\n");
        exit(1);
   
}

    state = pthread_join(t_id, &t_return);

    //thread 종료시까지 메인함수의 실행 지연.

    //리턴 값을 저장.

 

    if(state != 0){
    puts("Thread join error");
    exit(1);
    }
   
printf("main function is end, Thread is returned. %s", (char*)t_return);
    free(
t_return); 
    return 0;
}

void *
thread_function(void *arg) //실행 함수
{
   
int i;
    char * p = (char*)
malloc(20*sizeof(char));
   
strcpy(p, "thread is over!\n");
    for(
i=0; i<3; i++)

    {
        sleep(2);
        puts("Thread is running..");

    }
    return p;
}


=====================================================================

실행화면

사용자 삽입 이미지

위 두번째 소스코드의 실행화면을 보면

Thread is running... 이라는 문구가 3번 출력된 것을 볼 수 있다.


1번째 소스랑 2번째 소스의 차이점은

thread_join 함수를 선언해줬나 혹은 안해줬나의 차이라고 볼 수 있다.

사용자 삽입 이미지

첫번째 소스의 경우는 윗 그림처럼

thread_create함수를 통해 thread가 생성된 후,

생성된 thread의 수행이 미쳐끝나기도 전에 process가 먼저 끝나는 과정이다

혹자는 main함수내에 선언되어있는

sleep(3);

이 부분을 더 길게 잡아주면 되지 않느냐라고 말 할 수도 있다.

물론 가능하다.

하지만 함수처리내용이 위예제처럼 간단해서 그렇지...복잡한 연산같은 경우

일일히 사람이 계산해서 sleep()에 값을 넣어줄 수는 없기 때문에

비실용적이라 할 수 있다.


사용자 삽입 이미지

두번째 소스의 경우는 윗 그림처럼

thread_create함수를 선언한 후, thread_join함수를 선언함으로써

생성된 thread의 연산이 끝날때까지 기다리고 있다가

해당 thread가 종료된 후에 process를 종료하게 되는 과정이다.

이렇게 함으로써 첫번째 소스의 결과값에서 볼 수 있었던 오류부분을

수정할 수가 있는 것이다.

 
반응형

'프로그래밍' 카테고리의 다른 글

기본 Thread 함수  (0) 2008.04.28
fork와 thread의 차이점  (0) 2008.04.28
이진 탐색 트리  (0) 2008.04.28
hungarian prefix  (0) 2008.04.26
break와 continue  (0) 2008.04.25
Posted by pmj0403