在同一个循环中集成pthread_create()和pthread_join()

Integrating pthread_create() and pthread_join() in the same loop

本文关键字:pthread 同一个 join 循环 create 集成      更新时间:2023-10-16

我是多线程编程的新手,我正在学习本教程。在本教程中,有一个简单的示例展示了如何使用pthread_create()pthread_join()。我的问题是:为什么我们不能把pthread_join()pthread_create()放在同一个循环中?

参考代码:
#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: %dn", 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: %dn", rc);
            return EXIT_FAILURE;
        }
    }
    /* block until all threads complete */
    for (i = 0; i < NUM_THREADS; ++i) {
        pthread_join(thr[i], NULL);
    }
    return EXIT_SUCCESS;
}

我明白了。对于其他有同样问题的用户,我在下面写下答案。

如果我们把pthread_join()pthread_create()放在同一个循环中,调用线程即main()将在创建线程1之前等待线程0完成它的工作。这将迫使线程顺序执行,而不是并行执行。因此,这会破坏多线程的目的。