【问题标题】:Why is pthread not using the given stack space?为什么 pthread 不使用给定的堆栈空间?
【发布时间】:2012-05-18 11:56:57
【问题描述】:

当创建一个新的pthread 并传递一个用pthread_attr_getstack 修改的参数时,它似乎没有使用定义的堆栈空间。

void* thread_function(void * ptr)
{
  int a;
  printf("stack var in thread %p\n",&a);
}


int main( int argc , char **argv )
{
  pthread_t thread;
  void * ptr = NULL;
  const int stack_size = 10*1024;

  void * stack = malloc(stack_size);
  printf("alloc=%p\n",&stack);

  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setstack( &attr , stack , stack_size );

  if (pthread_create(&thread, &attr, &thread_function , ptr ) ) {
    printf("failed to create thread\n");
    return 1;
  }

  pthread_attr_destroy(&attr);
  pthread_exit( 0 );
  return 0;
}

不幸的是输出是:

alloc=0x7fff48989bc8
stack var in thread 0x7f6e6f0d2ebc

即使堆栈向后增长(我不确定)指针值差异很大,那只希望创建的线程使用不同的虚拟内存地址空间。但我认为情况并非如此。

【问题讨论】:

  • 为什么不打印分配内存的地址而不是局部变量'stack'的地址?我的意思是:printf("alloc=%p\n",stack);
  • @Adriano 他也这样做。这就是我们可以看到局部变量不在分配区域内的方式。
  • @nos 我错过了一些东西! :O malloc 将在堆上分配(比如地址 100)。 'stack' 分配在 main 的堆栈上(比如地址 10)。如果一切正常,变量“a”应该(或多或少)位于地址 100。但如果您打印 &stack 的地址,您将看到 10,而不是 100。

标签: c memory pthreads stack


【解决方案1】:

你打印错了,

printf("alloc=%p\n",&stack);

打印本地堆栈变量的地址,而不是分配的内存。你必须这样做

printf("alloc=%p\n",stack);

另外,您需要检查错误:

错误

   pthread_attr_setstack() can fail with the following error:

   EINVAL stacksize is less than PTHREAD_STACK_MIN (16384) bytes.  On some
          systems, this error may also occur if stackaddr or
          stackaddr + stacksize is not suitably aligned.

您只设置了 10kB 的堆栈,因此请使用更大的堆栈重试,并检查 pthread_attr_setstack 的返回值。

我可能也会尝试使堆栈页面对齐。

【讨论】:

  • 为了安全起见,您可能还想使用posix_memalign 之类的东西。
猜你喜欢
  • 2021-03-05
  • 1970-01-01
  • 2018-08-02
  • 2013-08-18
  • 2011-05-28
  • 2011-01-30
  • 2013-03-26
  • 2013-06-16
  • 2012-04-09
相关资源
最近更新 更多