为什么我的 pthread_t 指针数组会在 pthread_create 上导致段错误,但对数组中 pthread_t 的引用不会
Why does my array of pthread_t pointers cause segfault on pthread_create, but references to pthread_t in the array does not
我想将 pthread_t
存储在数组中,如下所示:
pthread_t tThreads[nThreads];
不久之后,我用 for 循环遍历数组以启动线程
pthread_create( &tThreads[i], NULL, &fn, (void*) NULL);
我注意到我正在创建一个 pthread_t
数组,在特定索引处使用 pthread_t
对象,然后传递对该 pthread_t
的引用以启动线程。为了让自己变得聪明并减少冗长,我将 tThreads
更改为 pthread_t
引用数组
pthread_t* tThreads[nThreads];
这样我就可以像这样创建线程
pthread_create( tThreads[i], NULL, &fn, (void*) NULL);
问题是第二种方法在尝试创建 pthread 时产生段错误。
是什么原因造成的?
使用 pthread_t tThreads[nThreads]
,您可以定义一个直接包含 pthread_t
对象的数组。您可以将每个此类有效对象的(地址)传递给 pthread_create
.
与 pthread_t* tThreads[nThreads]
相比,您定义了 指针数组 到 pthread_t
-objects 但不是 pthread_t
-objects 本身.
将这样一个(未初始化的)指针(指向 "somewhere" 但不是有效的 pthread_t
对象)传递给 pthread_create
将产生未定义的行为(例如段错误)。每次通话前都需要 tThreads[i] = malloc(sizeof(pthread_t))
。
我想将 pthread_t
存储在数组中,如下所示:
pthread_t tThreads[nThreads];
不久之后,我用 for 循环遍历数组以启动线程
pthread_create( &tThreads[i], NULL, &fn, (void*) NULL);
我注意到我正在创建一个 pthread_t
数组,在特定索引处使用 pthread_t
对象,然后传递对该 pthread_t
的引用以启动线程。为了让自己变得聪明并减少冗长,我将 tThreads
更改为 pthread_t
引用数组
pthread_t* tThreads[nThreads];
这样我就可以像这样创建线程
pthread_create( tThreads[i], NULL, &fn, (void*) NULL);
问题是第二种方法在尝试创建 pthread 时产生段错误。 是什么原因造成的?
使用 pthread_t tThreads[nThreads]
,您可以定义一个直接包含 pthread_t
对象的数组。您可以将每个此类有效对象的(地址)传递给 pthread_create
.
与 pthread_t* tThreads[nThreads]
相比,您定义了 指针数组 到 pthread_t
-objects 但不是 pthread_t
-objects 本身.
将这样一个(未初始化的)指针(指向 "somewhere" 但不是有效的 pthread_t
对象)传递给 pthread_create
将产生未定义的行为(例如段错误)。每次通话前都需要 tThreads[i] = malloc(sizeof(pthread_t))
。