2016-07-01 6 views
0

저는 멀티 스레드 프로그래밍에 익숙하지 않고 this tutorial을 따르고 있습니다. 이 자습서에는 pthread_create()pthread_join()을 사용하는 방법을 보여주는 간단한 예제가 있습니다. 내 질문 : pthread_join()pthread_create()과 같은 루프에 넣을 수없는 이유는 무엇입니까? 참조동일한 루프에서 pthread_create()와 pthread_join() 통합

코드 :

#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 

#define NUM_THREADS 2 

/* create thread argument struct for thr_func() */ 
typedef struct _thread_data_t { 
    int tid; 
    double stuff; 
} thread_data_t; 

/* thread function */ 
void *thr_func(void *arg) { 
    thread_data_t *data = (thread_data_t *)arg; 

    printf("hello from thr_func, thread id: %d\n", data->tid); 

    pthread_exit(NULL); 
} 

int main(int argc, char **argv) { 
    pthread_t thr[NUM_THREADS]; 
    int i, rc; 
    /* create a thread_data_t argument array */ 
    thread_data_t thr_data[NUM_THREADS]; 

    /* create threads */ 
    for (i = 0; i < NUM_THREADS; ++i) { 
     thr_data[i].tid = i; 
     if ((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))) { 
      fprintf(stderr, "error: pthread_create, rc: %d\n", rc); 
      return EXIT_FAILURE; 
     } 
    } 
    /* block until all threads complete */ 
    for (i = 0; i < NUM_THREADS; ++i) { 
     pthread_join(thr[i], NULL); 
    } 

    return EXIT_SUCCESS; 
} 

답변

2

나는 그것을 알아 냈다. 같은 질문을 가진 다른 사용자의 경우 답변 아래에 글을 남깁니다. 우리 pthread_create()와 같은 루프에서 pthread_join() 넣으면

, 호출 스레드 즉 main()이 아닌 병렬로 순차적으로 실행하기 위해 스레드를 강제 스레드 생성 1. ​​이전 작업을 완료 스레드 0을 기다릴 것이다. 따라서 멀티 스레딩의 목적을 없앨 수 있습니다.