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

Son*_*hra 1 c++ multithreading posix pthreads pthread-join

我是多线程编程的新手,我正在学习本教程。在本教程中,有一个简单的示例展示了如何使用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: %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;
}
Run Code Online (Sandbox Code Playgroud)

Son*_*hra 7

我想到了。对于有相同问题的其他用户,我写在答案下方。

如果我们将 与pthread_join()放在同一个循环中pthread_create(),调用线程 iemain()将在创建线程 1 之前等待线程 0 完成其工作。这将强制线程按顺序执行,而不是并行执行。因此它会扼杀多线程的目的。