-
pthread_create 예제 (쓰레드 생성)C_C++ 프로그래밍 2019. 5. 25. 01:03
개발 환경
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)
세번째 파라미터 : 분기시켜서 실행하게 될 쓰레드 함수
네번째 파라미터 : 쓰레드 함수가 넘겨받을 매개변수
소스코드
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364#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(); // 프로세스의 idtid = 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 endpthread_join(p_thread[0], (void **)&status);pthread_join(p_thread[1], (void **)&status);return 0;}실행결과
123456789[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 --- 2cs 각각의 쓰레드가 같은 프로세스에서 다른 식별자를 가지고 돌아가는 것을 알 수 있다.
※ 본 글은 개인 포트폴리오 혹은 공부용으로 사용하기 때문에, 무단 복사 유포는 금지하지만, 개인 공부 용도로는 얼마든지 사용하셔도 좋습니다
반응형'C_C++ 프로그래밍' 카테고리의 다른 글
thread_exit(쓰레드에서 특정 값을 return을 시키자) (0) 2019.05.25 pthread_detach(쓰레드 자원들을 분리시키자) (0) 2019.05.25 pthread_join(쓰레드의 종료를 대기한다) (0) 2019.05.25 [C] pthread의 기본 구조와 함수들 (0) 2019.05.24