Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在同一循环中集成pthread_create()和pthread_join()_C++_Multithreading_Pthreads_Posix_Pthread Join - Fatal编程技术网

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

C++ 在同一循环中集成pthread_create()和pthread_join(),c++,multithreading,pthreads,posix,pthread-join,C++,Multithreading,Pthreads,Posix,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 struc

我是新的多线程编程,我以下。在本教程中,有一个简单的示例演示如何使用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;
}

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


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

我发现了这一点。对于其他有同样问题的用户,我在下面写下答案

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