3

pthread_create 的第一个参数是一个 pthread_t 指针。在下面的hello 程序中,如果第一个参数是指向 pthread_t ( pthread_t*) 而不是pthread_t ( ) 的指针,pthread_t则程序以Segmentation fault...为什么结束?

我不记得看到pthread_t*. 的第一个参数的声明类型pthread_create
Butenhof 的书Programming with POSIX Threads的第 2 章说:

要创建一个线程,您必须声明一个类型为pthread_t[not pthread_t*] 的变量。

但是根据规范,第一个参数pthread_create是指向的指针pthread_t,那么为什么会出现分段错误呢?



分段故障

pthread_t* thr;
pthread_create(thr, NULL, &hello, NULL);



运行正常

pthread_t thr;
pthread_t* pntr = &thr;
pthread_create(pntr, NULL, &hello, NULL);



你好程序:

#include <pthread.h>
#include <stdio.h>

void * 
hello(void *arg){
  printf("Hello\n");
  pthread_exit(NULL);
}

int 
main(int argc, char **argv){
  pthread_t thr = 1;
  pthread_create(&thr, NULL, &hello, NULL);



  pthread_join(thr, NULL);

  return 0;
}

pthread_create 原型:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
4

3 回答 3

9
pthread_t* thr;
pthread_create(thr, NULL, &hello, NULL);

declares a pointer to a pthread_t without allocating storage for it. When you call pthread_create, it'll try writing to *thr. This is at an undefined location and will almost certainly fail.

pthread_t thr;
pthread_t* pntr = &thr;
pthread_create(pntr, NULL, &hello, NULL);

works because you've declare storage (thr on the stack) for a pthread_t.

Note that the second, working, version can be simplified to what is used in your hello program

pthread_t thr;
pthread_create(&thr, NULL, &hello, NULL);

...which declares a pthread_t on the stack then passes a pointer to it into pthread_create.

于 2012-12-19T16:03:02.813 回答
4

这是因为如果你简单地声明一个指针,你不能指望它指向分配的、初始化的内存。

当您改为声明 apthread_t时,它会被分配自己的一小块内存,然后您可以使用&运算符获取地址并将其传递给pthread_create.

于 2012-12-19T16:03:54.717 回答
0

如果你想创建一些线程,你可以使用下面的代码:

pthread_t* thread_handles;
thread_handles = malloc(thread_count * sizeof(pthread_t));
for (thread = 0; thread < thread_count; thread++)
{
  pthread_create(&thread_handles[thread], NULL, threadFunc, (void*)input);
}

这样,您应该在调用之前为您的句柄分配内存pthread_create,就像当您想要创建一些“结构”时,您应该首先为它们分配内存。

于 2016-05-22T11:13:57.843 回答