본문 바로가기
C_C++ 프로그래밍

pthread_create 예제 (쓰레드 생성)

by RoJae 2019. 5. 25.

개발 환경

 OS

 Ubuntu 18.04.2

 컴파일러

 gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04)






 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,

void *(*start_routine)(void *), void *arg);


 첫번째 파라미터 : 쓰레드 식별자

 두번쨰 파라미터 : 쓰레드 특성 (기본은 NULL)

 세번째 파라미터 : 분기시켜서 실행하게 될 쓰레드 함수

 네번째 파라미터 : 쓰레드 함수가 넘겨받을 매개변수



소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
 
//  int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//  void *(*start_routine)(void *), void *arg);
//  첫번째 파라미터 : 쓰레드 식별자
//  두번쨰 파라미터 : 쓰레드 특성 (기본은 NULL)
//  세번째 파라미터 : 분기시켜서 실행하게 될 쓰레드 함수
//  네번째 파라미터 : 쓰레드 함수가 넘겨받을 매개변수
void *thread_function(void *data){
        pid_t pid;
        pthread_t tid;
 
        char* thread_name = (char*) data;
        pid = getpid();         // 프로세스의 id
        tid = pthread_self();   // pthread 식별
 
        int i = 0;
 
        while(i < 3){
                // pthread 이름, id, 식별자, loop횟수 
                printf("[%s] pid : %u, tid:%x --- %d\n",
                                thread_name, (unsigned int) pid, (unsigned int) tid,i);
                i++;
                sleep(1);
        }
}
int main(){
        pthread_t p_thread[2];
        int thr_id;
        int status;
        char p1[] = "thread_1";
        char p2[] = "thread_2";
        char pp[] = "thread_Main";
 
        sleep(1);
 
        // 1번 쓰레드 생성
        thr_id = pthread_create(&p_thread[0], NULL, thread_function, (void *) p1);
 
        if(thr_id < 0)
                perror("쓰레드 생성 실패");
 
        // 2번 쓰레드 생성
        thr_id = pthread_create(&p_thread[1], NULL, thread_function, (void *) p2);
 
        if(thr_id < 0)
                perror("쓰레드 생성 실패");
 
        // main함수에서도 쓰레드가 실행되고 있는 동일한 함수 실행
        thread_function((void *) pp);
 
        // wating pthread end
        pthread_join(p_thread[0], (void **)&status);
        pthread_join(p_thread[1], (void **)&status);
 
        return 0;
}
 

cs





실행결과

1
2
3
4
5
6
7
8
9
[thread_1] pid : 5645, tid:ecaa700 --- 0
[thread_Main] pid : 5645, tid:f4c2740 --- 0
[thread_2] pid : 5645, tid:e4a9700 --- 0
[thread_1] pid : 5645, tid:ecaa700 --- 1
[thread_2] pid : 5645, tid:e4a9700 --- 1
[thread_Main] pid : 5645, tid:f4c2740 --- 1
[thread_2] pid : 5645, tid:e4a9700 --- 2
[thread_1] pid : 5645, tid:ecaa700 --- 2
[thread_Main] pid : 5645, tid:f4c2740 --- 2
cs

각각의 쓰레드가 같은 프로세스에서 다른 식별자를 가지고 돌아가는 것을 알 수 있다.


※ 본 글은 개인 포트폴리오 혹은 공부용으로 사용하기 때문에, 무단 복사 유포는 금지하지만, 개인 공부 용도로는 얼마든지 사용하셔도 좋습니다


반응형

댓글