pthread, 언제 어떻게 실행되는 건가요 ?
글쓴이: bushi / 작성시간: 금, 2007/04/13 - 8:06오후
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
static int ncount;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct loops_s {
const char *name;
void *data;
};
void *do_loop(void *data)
{
int i;
struct loops_s *lop = (struct loops_s *)data;
int id = *(int*)(lop->data);
int mydata;
for (i = 0; i < 3; i++) {
pthread_mutex_lock(&mutex);
ncount++;
mydata = ncount;
pthread_mutex_unlock(&mutex);
printf("%s i:%d c:%d\n", lop->name, id, mydata);
usleep(1);
}
pthread_exit(NULL);
return 0;
}
int main(int argc, char **argv)
{
int thr_ret;
pthread_t p_thread[2];
int i = -1;
struct loops_s loops[2] = {
{.name = "#1", .data = NULL},
{.name = "#2", .data = NULL}
};
ncount = 0;
for (i = 1; i < 3; i++) {
loops[i-1].data = &i;
thr_ret = pthread_create(&p_thread[i-1], NULL, do_loop,
&loops[i-1]);
if (argc == 1)
usleep(1);
}
if (argc == 2)
usleep(1);
for (i = 0; i< 2; i++) {
pthread_join(p_thread[i], NULL);
}
return 0;
}실행 결과
[bushi@rose net]$ ./t #1 i:1 c:1 #2 i:2 c:2 #1 i:1 c:3 #2 i:2 c:4 #1 i:1 c:5 #2 i:2 c:6 [bushi@rose net]$ ./t 0 #1 i:3 c:1 #2 i:3 c:2 #1 i:3 c:3 #2 i:3 c:4 #1 i:3 c:5 #2 i:3 c:6 [bushi@rose net]$ ./t 0 0 #1 i:0 c:1 #2 i:0 c:2 #1 i:0 c:3 #2 i:0 c:4 #1 i:0 c:5 #2 i:0 c:6 [bushi@rose net]$
첫번째와 두번째는 이해가 됩니다. 마지막 세번째는 왜 저러는 건가요 ?
얼토당토 않은 0 이 왜 출력되는지 모르겠습니다.
Forums:


세번째는, argc 값이
세번째는, argc 값이 3이고, 따라서 main에 있는 두 곳의 usleep()이 다 불리지 않으니, main의 마지막 for 루프 진입해서 i가 0으로 초기화되고 join이 불리면서 블럭된 다음에야 두 개의 스레드가 처음으로 실행이 되었네요. 따라서 두 스레드 모두 int id = *(int*)(lop->data); 의 결과는 id = 0 :-D
좋은 하루 되세요!
감사합니다. join 을
감사합니다. join 을 위한 for 루프에서 i 가 초기화되는 것을 놓치고 있었네요.
이 글을 보시던
이 글을 보시던 분들을 위해 덧 붙입니다.
눈으로 확인해 보시려면 do_loop() 안의 usleep() 을 comment out 해보세요.
printf()를 사용하지 말고, 버퍼에 때려박고 나중에 한꺼번에 출력하도록 하면 좀 더 분명합니다.
댓글 달기