【问题标题】:Stack address for Thread and the main process线程和主进程的堆栈地址
【发布时间】:2013-06-12 17:51:47
【问题描述】:

我有一个关于线程和进程的内存地址的问题。问题是:- 在正常通话中像

int func(int a, int b){
    int c;
    c = a + b;
    return c;
}         

int main(){
    int ret = func(a,b);
     return 0;
}

在上面对函数 func 的函数调用中,函数变量 a 和 b 将被存储在堆栈中。如果我错了,请纠正我。

现在另一种情况是当我们从主进程创建线程时。

void * func(void *dummy_ptr){
    int c;
    c = a + b;
    pthread_exit();
}         

int main(){
    pthread_t  id;
    int ret = pthread_create(&id, NULL, & func(), NULL);
    return 0;
}

我的问题是 pthread_create 的变量将存储在哪里。它是存储在主堆栈还是线程堆栈上。

【问题讨论】:

  • 您的示例无法编译,因为您错过了声明 ab

标签: process pthreads


【解决方案1】:

pthread_create 在堆中为新线程的堆栈分配空间。所以func里面的变量存储在线程的栈中,而栈本身也位于程序的堆中。

【讨论】:

  • 是的,这是正确的。对于在 pthread_create api 中调用的函数 func() 变量,变量将存储在线程的堆栈中,但是我们在 API pthread_create() 中传递的变量呢,例如 pthread_t id,任何线程属性和最后一个参数像一些整数或结构指针一样传递。
【解决方案2】:

变量pthread_t id是main的局部变量,所以它必须在main的栈上创建。

main 完成执行并且,

  • main 中没有 pthread_join 来等待线程终止。
  • 线程未分离。

main 退出导致所有其他线程突然终止(杀死)。

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 2019-07-11
    相关资源
    最近更新 更多