리눅스에서 쓰레드 시작한지 1시간 된 초보입니다.
글쓴이: vktod25 / 작성시간: 금, 2013/12/27 - 4:27오후
Beginning linux programing이라는 책에 쓰레드부분을 읽다가 의문점이 들어 질문해봅니다.
한 프로세스에 2개의 쓰레드가 동시 실행되는 실습예제 인데요.
printf의 내용이 왜 실시간으로 나오지 않고 프로그램이 완료되면 뙇! 하고 한번에 결과가 보여지는건가요?
#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 run_now =1;
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);
}
int print_count1 = 0;
while(print_count1++ <20) {
if(run_now == 1){
printf("1");
run_now=2;
}
else{
sleep(1);
}
}
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\n");
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg){
int print_count2 = 0;
while (print_count2++ <20){
if(run_now ==2){
printf("2");
run_now =1;
}
else{
sleep(1);
}
}
}Forums:


printf 함수가 버퍼링을 하기때문입니다.
출력을 바로 보고싶으시면 "fflush(stdout);" 을 printf 밑에 추가하시면 바로 출력됩니다.
아 정말.
방대한 지식에 몸이 쑤그러 드네요 ㅠㅠ 저는 언제쯤 그정도의 수준이 될 수 있을까요
gilgil.net
standard stream의 buffering을 참고하시기 바랍니다.
http://www.pixelbeat.org/programming/stdio_buffering/
www.gilgil.net
리눅스는 개행 전까지는 출력을 보류합니다.
printf("1");
이걸
printf("1\n");
으로 바꿔서 해보세요.
댓글 달기