Creative Code

04_THREAD1.c 본문

Raspberry PI(C)

04_THREAD1.c

빛하루 2023. 10. 6. 12:59
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void* thread1_main(void *arg)
{
    int i;
    int cnt = *((int*)arg);

    for (i = 0; i < cnt; i++)
    {
        sleep(1); puts("running thread..1\n");
    }

    return 10;
}

void* thread2_main(void *arg)
{
    int i;
    int cnt = *((int*)arg);

    for (i = 0; i < cnt; i++)
    {
        sleep(1); puts("running thread..2\n");
    }

    return NULL;
}

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

    if (pthread_create(&t1_id /*쓰레드의 ID저장을 위한 변수의 주소 값 전달 */,
     NULL /*스레드에 부여할 정보의 전달을 위한 변수 NULL이면 가장 기본적인 스레드 생성*/
    , thread1_main /*실행하고자 하는 함수 명*/,
     (void*)&thread_param) != 0 /*인자의 정보를 담고있는 변수의 주소값*/)
    {
        puts("pthread_create() error\n");
        return -1;
    }

    if (pthread_create(&t2_id, NULL, thread2_main, (void*)&thread_param) != 0)
    {
        puts("pthread_create() error\n");
        return -1;
    }


    //블로킹 함수(스레드가 끝날때까지 다음 명령을 진행하지 않음). t1_id가 끝날때까지 대기
    if (pthread_join(t1_id, &thr_ret)!=0) {
        puts("pthread_join() error");
        return -1;
    }
    printf("%d\n",(int *)thr_ret);

    sleep(3); puts("end of main\n");

    return 0;
}

'Raspberry PI(C)' 카테고리의 다른 글

06_THREAD3.c  (0) 2023.10.06
05_THREAD2.c  (0) 2023.10.06
03_THREAD.c  (0) 2023.10.06
02_SWITCH_LED_INTERRUPT.c  (0) 2023.10.06
01_LED_ON_OFF.c  (0) 2023.10.06