2016-07-01 4 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()と同じループを入れると、呼び出し元のスレッドmain()は、スレッド0を作成する前にスレッド0が終了するのを待ってスレッド1を作成します。したがって、マルチスレッド化の目的を打ちのめすことになります。

関連する問題