troubleshoot of dev

pthread를 사용하여 이벤트를 받아 처리하는 thread 생성하기

도비야 산책가자 2020. 5. 31. 21:12

이전에 pthread를 windows기반 visual studio에서 설정하는 것을 작성했다.

이번에는 이벤트를 별도의 thread로 처리 할 수 있도록 하는 부분을 작성했고, 해당 부분을 공유하고자 한다.

 

pthread_t타입의 commandThreadHandle을 선언하고, 사용하기 위해 pthread_create()한다.

 

1. pthread_create

pthread_create는 아래와 같이 구성되어 있으며 thread는 쓰레드 식별시 사용되는 식별자다. attr은 특성 지정용이며 기본일 경우 NULL을 사용한다. start_routine은 실행할 함수며, 네번째 인자인 arg는 넘겨준 매개변수이다.

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

성공적으로 생성될 경우 0을 리턴하기 때문에 정상적으로 생성되었는지 확인하는 조건문에 싸서 사용하기도 한다.

pthread_t commandThreadHandle; //선언
pthread_create(&commandThreadHandle, NULL, command_thread, NULL); //create

void command_thread(){
..실행하고자 하는 내용..
}

2. pthread_join

이 상태로 main에 선언 후 사용하면 pthread내부가 실행이 잘 되지 않는 것을 확인 할 수 있다.

그 이유는 thread실행하는 것을 main이 기다리지 않기 때문에 main이 종료되며 끝이 나는 건데. 이것을 기다릴 수 있도록 해주는 문법이 있다. 

thread는 위와 같이 식별자 두번째는 thread_return 값. 나의 경우는 status로 받아서 성공(0값) or 에러 코드를 받아올 수 있도록 했다.

int pthread_join(pthread *thread, void **thread_return)

 

아래는 작성한 코드다.

계속 반복해서 command를 받을 수 있도록 했으며,

getchar에서 Enter를 개행문자로 받아 default결과를 계속 return하기 때문에 개행문자가 들어오면 getchar를 하도록했다. z입력시 반복문 조건을 false로 바꿔주는 것을 통해 끝낼 수 있도록 했다.

//Author e-mail : vertex50@naver.com

#define HAVE_STRUCT_TIMESPEC

#include <iostream>
#include <pthread.h>

int flag = 1;

void* command_thread(void*) {

while (flag) {
char cmd;
printf("입력 : ");

cmd = getchar();
if (cmd == '\n') {
cmd = getchar();
}

switch (cmd) {
case 'a':
printf("A Button Pressed \n");
break;
case 'b':
printf("B Button Pressed \n");
break;
case 'c':
printf("C Button Pressed \n");
break;
case 'z':
flag = 0;
break;
default:
printf("Unsupported Func.. \n\n\n");
break;
}

if (flag == 0) { //finish thread
printf("END while \n\n\n");
return 0;
}
}//end while
}

int main() {
pthread_t commandThreadHandle;
int status;

if (pthread_create(&commandThreadHandle, NULL, command_thread, NULL) < 0) {
perror("thread create error:");
return 0;
}

pthread_join(commandThreadHandle, (void**)&status);
printf("Thread End %d\n", status);
return 0;

결과 :

예쁘게 z 입력 들어오기 전까지 계속 이벤트 thread를 반복한다.