在同一个循环中集成pthread_create()和pthread_join()
Integrating pthread_create() and pthread_join() in the same loop
我是多线程编程的新手,我正在学习本教程。在本教程中,有一个简单的示例展示了如何使用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完成它的工作。这将迫使线程顺序执行,而不是并行执行。因此,这会破坏多线程的目的。
相关文章:
- 为什么std::async使用同一个线程运行函数
- 多个"常量引用"变量可以共享同一个内存吗?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 在 c++11 中为 pthread 设置调度参数
- 为什么同一个变量的内存地址不同?
- 两个进程可以通过跟踪附加到同一个 PID 吗?
- 如何在同一个 CMAKE 项目中强制链接到共享库?
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- pthread只有在线程数量较少时才可以正常工作
- 不同C++文件中未命名命名空间中的名称可以引用同一个命名事物吗?
- 我应该如何使用 epoll 从同一个 FD 读取和写入
- pthread执行时间比顺序执行时间差
- cuda:多个线程访问同一个全局变量
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- 使用 -pthread 如何不违反 ODR 规则?
- 如何将不同的函数签名映射到同一个 std::map?
- 使用 pthread 的多线程
- 多个线程可以读取同一个类成员变量吗?