C++ 在同一循环中集成pthread_create()和pthread_join()
我是新的多线程编程,我以下。在本教程中,有一个简单的示例演示如何使用pthread_create和pthread_join。我的问题:为什么我们不能将pthread_join与pthread_create放在同一个循环中 参考代码: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
#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完成其工作。这将强制线程按顺序执行,而不是并行执行。因此,它将扼杀多线程的目的