C pthread,指针丢失内容

标签 c pointers pthreads

我正在尝试使用线程的返回值。为此,我刚刚找到了以下文章: How to return a value from thread in C

所以我使用下面的代码:

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

void *myThread()
{
   int ret = 42;
//   printf("%d\n", ret);
   printf("%p\n",(void*)&ret);

   void * ptr = (void*)&ret;
   printf("%p\n", ptr);
   printf("%d\n", *((int *)ptr));
   return (void*) &ret;
}

int main()
{
   pthread_t tid;
   static void *status;

//   int ret = 42;
//   status = &ret;
//   printf("%d\n", *((int *)status));

   pthread_create(&tid, NULL, myThread, NULL);
   pthread_join(tid, &status);

   printf("%p\n",((int *)status));  
   printf("%d\n", *((int *)status));
   return 0;
}

输出是: 0x7f7ead136f04, 0x7f7ead136f04, 42, 0x7f7ead136f04, 0

为什么最后一个值不是 42?

同样的问题:

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

     void* aufgabe_drei_thread() {
         int i = 5;
         return &i; 
     }

int main(int argc, char** argv) { 
    int* ptr_wert_aus_drei;
    pthread_t thread_three_id;
    pthread_create(&thread_three_id, NULL, aufgabe_drei_thread, NULL);
    pthread_join (thread_three_id, &ptr_wert_aus_drei);
    printf("Der Wert aus Thread 3 ist: %d\n", *((int *)ptr_wert_aus_drei));

     return (EXIT_SUCCESS);
}

输出是:Der Wert aus Thread 3 ist:32508 而不是 5。

我做错了什么?

最佳答案

在堆上分配以挂起该值,或传递一个指针来存储它。

这个:

void *myThread(void *opaque)
{
   int *ret = malloc(sizeof(int));
   *ret = 42;
//   printf("%d\n", *ret);
   printf("%p\n",(void*) ret);

   void * ptr = (void*) ret;
   printf("%p\n", ptr);
   printf("%d\n", *((int *)ptr));
   return (void*) ret;
}

或者这个:

void *myThread(void *opaque)
{
   int *ret = (int *) opaque;
   *ret = 42;
//   printf("%d\n", *ret);
   printf("%p\n",(void*) ret);

   void * ptr = (void*) ret;
   printf("%p\n", ptr);
   printf("%d\n", *((int *)ptr));
   return NULL;
}

像这样传递变量时:

pthread_create(&tid, NULL, myThread, &status);
pthread_join(tid, NULL);

关于C pthread,指针丢失内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36877093/

相关文章:

linux - pthread_rwlock_init() 导致段错误

c - 在 C 中重投的特定骰子

c - 如何在字符串中搜索特定字符、数字或标点符号

c - 输入比较不正常,总是去失败的情况下,为什么?

c - (段错误)读取变量时出错,无法读取地址 X 处的变量

c - 虚假唤醒后的互斥锁状态

python - 如何在 Python 中使用具有复杂类型的 C 函数?

python - 使用 ctypes 从 Python 调用带有 Char** 参数的 C 方法

直接从 typedef 结构定义创建指针

c - 如何在给定时刻创建线程