C언어 스레드 질문
글쓴이: spring7s / 작성시간: 화, 2022/05/03 - 11:26오후
이 코드를 실행해서 ox를 순서대로 20번 출력해야하는데 왜 중간에 xoox로 나오는 지 모르겠습니다.
#include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> int myglobal; void *thread_function(void *arg) { int i, j; for(i=0;i<20;i++){ j=myglobal; j=j+1; printf("x"); fflush(stdout); sleep(1); myglobal=j; } return NULL; } int main(void){ pthread_t mythread; int i; if(pthread_create(&mythread, NULL, thread_function, NULL)){ printf("ldquo:error creating thread."); abort(); } for(i=0;i<20;i++){ myglobal=myglobal+1; printf("o"); fflush(stdout); sleep(1); } }
File attachments:
첨부 | 파일 크기 |
---|---|
![]() | 2.65 KB |
Forums:
왜 두 스레드가 교대로 출력할 거라고 생각하죠?
왜 두 스레드가 교대로 출력할 거라고 생각하죠? 약속이라도 하나요?
질문자님이 모르니까 물어 볼 수 있는거지 왜이리
질문자님이 모르니까 물어 볼 수 있는거지 왜이리 까칠해요.. ㅋ
@질문자님
쓰레드는 실행순서와 비례해서 실행되지 않습니다.
아래 글타래 참고해보세요~
https://kldp.org/node/120115
sleep()의 정밀도가 높지 않습니다. 적어도 >
sleep()의 정밀도가 높지 않습니다. 적어도 > 10ms 이상된다고 보셔야 되고... 그래서 각 'O', 'X' 문자를 찍은 시점에 차이가 날 수 있습니다.
반드시 순서대로 찍어야 한다면 세마포 등의 IPC (Inter Process Communication) 방법을 쓰셔야 합니다.
댓글 달기