개발자/Linux 리눅스

라즈베리파이에서 리눅스 다중 Thread 프로그램 구현

지구빵집 2017. 11. 15. 09:40
반응형

 

 

 

리눅스에서 다중 쓰레드 프로그램을 구현하는 방법을 알아보자. 플랫폼은 라즈베리파이고, 복잡하지 않고 리눅스 api를 사용해 쉽고 간단하게 구현할 수 있다.

 

라즈베리파이에서 리눅스 다중 Thread 프로그램 구현

 

Thread의 장 단점이 중요한 게 아니라 굉장히 많이 사용한다. 사실 Thread를 사용하지 않는 프로그램은 거의 없다. 작업을 동시에 실행한다는게 얼마나 멋진 일인가?

 

일단 가장 단순한 다중 Thread 프로그램을 보자. 근데 책의 예제라 그런지 무지하게 복잡하고, 어렵게 보인다. 으~ 이런거 정말 싫은데. 그냥 설명만 하고 쉬운건 아래에 있다. 여러가지 소스코드를 참고하자.

 

 

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
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
 
void *thread_function(void *arg);
 
char message[] = "Hello World";
 
int main() {
    int res;
    pthread_t a_thread;
    void *thread_result;
    res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
    if (res != 0) {
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }
    printf("Waiting for thread to finish...\n");
    res = pthread_join(a_thread, &thread_result);
    if (res != 0) {
        perror("Thread join failed");
        exit(EXIT_FAILURE);
    }
    printf("Thread joined, it returned %s\n", (char *)thread_result);
    printf("Message is now %s\n", message);
    exit(EXIT_SUCCESS);
}
 
void *thread_function(void *arg) {
    printf("thread_function is running. Argument was %s\n", (char *)arg);
    sleep(3);
    strcpy(message, "Bye!");
    pthread_exit("Thank you for the CPU time");
}
 
cs

 

컴파일

 

1
$ gcc -o thread1 thread1.c -lpthread
cs

 

실행명령과 결과

 

1
2
3
4
5
6
 $ ./thread1
Waiting for thread to finish...
thread_function is running. Argument was Hello World
Thread joined, it returned Thank you for the CPU time
Message is now Bye!
 
cs

 

 

가장 먼저 해야 할 일은 스레드가 실행할 함수를 선언한다.

 

void *thread_function(void *arg);

 

메인 함수에서 몇 가지 지역 변수를 설정하고 pthread_create 를 호출해서 새 스레드를 실행한다.

 

 

pthread_t a_thread;

void *thread_result;

 

res = pthread_create(&a_thread, NULL, thread_function, (void *)message);

 

pthread_create 함수의 첫 매개변수는 생성한 스레드를 참조하는 데 사용하는 pthread_t 객체의 주소 지정, 둘째 매개변수는 NULL, 그 다음 스레드 실행할 함수 이름, 다음이 스레드에 넘겨줄 인자의 주소이다.

 

새 스레드가 시작되었는지 점검하고 pthread_join을 호출한다.

 

res = pthread_join(a_thread, &thread_result);

 

해당 스레드가 종료될 때까지 기다리다가 실행을 반환한다. 

 

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

 

하~ 어쩌면 좋니, 가을이 다 갔어. 가을에 빠진 라즈베리파이 ^^

 

 

가을에 빠진 라즈베리파이

 

가을에 빠진 라즈베리파이

 

 

 

 

반응형