c - pthread_join和void **-错误理解

标签 c compiler-errors pthreads pthread-join

我写了一个简单的任务,如下所示。它打印一个字符串,增加全局变量glob,然后通过pthread_exit将其值返回给pthread_join。

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

int glob = 0;

void *task()
{
    printf("I am a simple thread.\n");
    glob++;
    pthread_exit((void*)&glob);
}

int main()
{
pthread_t   tid;
int         create = 1;
void        **ppvglob;


    create = pthread_create(&tid, NULL, task, NULL);
    if (create != 0)    exit(EXIT_FAILURE);
    
    pthread_join(tid, ppvglob);
    
    int **ppv = (int**)ppvglob;
    printf("Variabile globale restituita alla terminazione del thread: %d\n", **ppv);                   
    
    return(0);
}
编译器给我错误:
main.c: In function ‘main’:
main.c:29:2: warning: ‘ppvglob’ may be used uninitialized in this function [-Wmaybe-uninitialized]
   29 |  pthread_join(tid, ppvglob);
      |  ^~~~~~~~~~~~~~~~~~~~~~~~~~
你能告诉我原因吗?

最佳答案

进行时:

pthread_join(tid, ppvglob);

因为您从未初始化过ppvglob,所以编译器通常会提出抗议,但实际上您必须替换:
void        **ppvglob;
....
pthread_join(tid, ppvglob);

通过:
void        *pvglob;
....
pthread_join(tid, &pvglob);

然后,当然:
int **ppv = (int**)ppvglob;
printf("Variabile globale restituita alla terminazione del thread: %d\n", **ppv);                   

通过:
int *pv = (int*)pvglob;
printf("Variabile globale restituita alla terminazione del thread: %d\n", *pv);


因此具有:
#include    <stdlib.h>
#include    <stdio.h>
#include    <pthread.h>

int glob = 0;

void *task()
{
    printf("I am a simple thread.\n");
    glob++;
    pthread_exit((void*)&glob);
}

int main()
{
  pthread_t   tid;
  int         create = 1;
  void        *pvglob;


  create = pthread_create(&tid, NULL, task, NULL);
  if (create != 0)    exit(EXIT_FAILURE);
    
  pthread_join(tid, &pvglob);
    
  int *pv = (int*)pvglob;
  printf("Variabile globale restituita alla terminazione del thread: %d\n", *pv);                   
    
  return(0);
}
编译与执行:
% gcc -Wall c.c -lpthread
% ./a.out
I am a simple thread.
Variabile globale restituita alla terminazione del thread: 1
打印1,因为这是glob的值

关于c - pthread_join和void **-错误理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62752275/

相关文章:

c - SOCK_SEQPACKET Unix 套接字上的空数据包

c++ - 线程没有从 sleep 中醒来

java - Swing Action 执行方法

c# - 注册表值更改错误(对象引用未设置为对象的实例)

c# - 错误说 system.void 不能从 c# 使用

c - pthreads:取消阻塞线程

c - 在 C 中释放结构后立即停止 pthread

c - printf ("%d","%u","%p",ptr,ptr,ptr) 和 printf ("%d %u %p",ptr,ptr,ptr) 有什么区别?

c - 为什么 const int main = 195 导致一个工作程序但没有 const 它以段错误结束?

c - 以双引号开头的行在 C 中是什么意思?