본문 바로가기

잡다한 IT/운영체제

pthread 관련 함수-1

■ pthread_create() : 쓰레드 생성


1
2
#include<pthread.h>
int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)



thread : 쓰레드가 성공적으로 생성되었을 때, 넘겨주는 쓰레드 식별 번호


attr : 쓰레드의 특성을 설정하기 위해서 사용한다. NULL 일 경우 기본 특성


start_routine : 쓰레드가 수행할 함수로 함수포인터를 넘겨준다.


arg : 쓰레드 함수 start_routine을 실행시킬 때, 넘겨줄 인자



■ pthread_join() : 쓰레드 종료/정리 ( process wait()함수와 비슷)


1
2
#include<pthread.h>
int pthread_join(pthread_t th, void **thread_return);



th : ptrhead_create에 의해서 생성된, 식별번호 th를 가진 쓰레드를 기다리겠다는 의미


thread_return : 식별번호 th인 쓰레드의 종료시 리턴값




■ pthread_self() 함수 : 현재 쓰레드 식별자 반환


1
pthread_t pthread_self(void);





▶ 컴파일 방법 : gcc -pthread 소스파일명



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
65
66
67
68
69
70
71
72
73
74
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
 
// 쓰레드 함수
void *t_function(void *data)
{
    pid_t pid;            // process id
    pthread_t tid;        // thread id
 
    pid = getpid();
    tid = pthread_self();
 
    char* thread_name = (char*)data;
    int i = 0;
 
    while (i<3)   // 0,1,2 까지만 loop 돌립니다.
    {
        // 넘겨받은 쓰레드 이름과 
        // 현재 process id 와 thread id 를 함께 출력
        printf("[%s] pid:%u, tid:%x --- %d\n"
            thread_name, (unsigned int)pid, (unsigned int)tid, i);
        i++;
        sleep(1);  // 1초간 대기
    }
}
 
int main()
{
    pthread_t p_thread[2];
    int thr_id;
    int status;
    char p1[] = "thread_1";   // 1번 쓰레드 이름
    char p2[] = "thread_2";   // 2번 쓰레드 이름
    char pM[] = "thread_m";   // 메인 쓰레드 이름
 
 
    sleep(1);  // 2초 대기후 쓰레드 생성
 
    // ① 1번 쓰레드 생성
    // 쓰레드 생성시 함수는 t_function
    // t_function 의 매개변수로 p1 을 넘긴다.  
    thr_id = pthread_create(&p_thread[0], NULL, t_function, (void *)p1);
 
    // pthread_create() 으로 성공적으로 쓰레드가 생성되면 0 이 리턴됩니다
    if (thr_id < 0)
    {
        perror("thread create error : ");
        exit(0);
    }
 
    // ② 2번 쓰레드 생성
    thr_id = pthread_create(&p_thread[1], NULL, t_function, (void *)p2);
    if (thr_id < 0)
    {
        perror("thread create error : ");
        exit(0);
    }
 
    // ③ main() 함수에서도 쓰레드에서 돌아가고 있는 동일한 함수 실행
    t_function((void *)pM);
 
    // 쓰레드 종료를 기다린다. 
    pthread_join(p_thread[0], (void **)&status);
    pthread_join(p_thread[1], (void **)&status);
 
    printf("메인 함수 종료\n");
 
    return 0;
}
 
 
출처: http://bitsoul.tistory.com/157 [Happy Programmer~]
cs


반응형

'잡다한 IT > 운영체제' 카테고리의 다른 글

polling 과 spin lock  (0) 2018.08.28
pthread 관련 함수-2  (0) 2018.08.16
MMU 와 MPU 의 차이점  (0) 2018.07.11
물리 메모리 관리  (0) 2018.05.04
스케줄링 고려할 점  (0) 2018.05.02