pthread_join出错

时间:2014-11-06 23:06:12

标签: c multithreading pthread-join

我的程序需要创建一些线程,但是我一直在pthread_join,因为它总是进入错误情况,因为返回(安全)是3而不是0,我认为这是正确的数字万一一切顺利。

编辑:为了更好地解释自己,错误是代码进入错误处理区域,当它不应该,这转换为我得到一个"错误等待:成功"消息。

int main() {    

  pthread_t tids[NUM_THREADS];
  int a, i, resultado, safe ;
  char *f ;

  f = (char *)malloc(sizeof(SIZEFICHEIRO));
  a = randomnum(4);
  f = pickfile(a, f);

  for ( i=0; i<NUM_THREADS ; i++ )
  {
    safe = pthread_create( &tids[i] , NULL , (void *)verificador , (void *) f) ;
    if ( safe != 0 )
        perror ("Error creating threads");
  }

  for ( i=0; i<NUM_THREADS ; i++ )
  {
    safe = pthread_join( tids[i], (void **)&resultado ) ;
    if ( safe != 0 )     // Error here
        perror ("Error waiting");

    printf("Result(0:Works ; -1:error) =  %d\n", resultado);
  }

}

2 个答案:

答案 0 :(得分:0)

safe = pthread_join( tids[i], (void **)&resultado ) ;
printf("%d", error );
if ( safe != 0 )     // Error here
    perror ("Error waiting");

如果pthread_join隐藏errno中的错误,就像大多数来电一样,问题在于您对printf的调用可以更改pthread_join隐藏的错误代码。如果您打算调用perror来打印错误,则需要在生成错误的函数返回后立即将其命名为

但是,pthread_join并未隐藏errno中的错误,它会返回错误。因此调用perror无法正常工作。你可以这样做:

if ( safe != 0 )     // Error here
{
    errno = safe;
    perror ("Error waiting");
}

if ( safe != 0 )
    printf ("Error waiting: %s\n", strerror (safe));

答案 1 :(得分:0)

测试了这段代码:

int main() 

{   

  pthread_t tids[NUM_THREADS];
  int a, i, resultado, safe ;
  char *f ;

  f = (char *)malloc(sizeof(SIZEFICHEIRO));
  a = randomnum(4);
  f = pickfile(a, f);

  for ( i=0; i<NUM_THREADS ; i++ )
  {
    safe = pthread_create( &tids[i] , NULL , (void *)verificador , (void *) f) ;
    if ( safe != 0 )
        perror ("Error creating threads");
  }

  for ( i=0; i<NUM_THREADS ; i++ )
  {
    safe = pthread_join( tids[i], (void **)&resultado ) ;
    if ( error != 0 )
        errno = safe;
        perror ("Error waiting");

    printf("Result(0:Works ; -1:error) =  %d\n", resultado);
  }
}

结果是:

Error waiting: Success
Result(0:Works ; -1:error) = 0
Error waiting: Success
Result(0:Works ; -1:error) = 0
Error waiting: No such process
Result(0:Works ; -1:error) = 0
Error waiting: No such process
Result(0:Works ; -1:error) = 0
Error waiting: No such process
Result(0:Works ; -1:error) = 0
Error waiting: No such process
Result(0:Works ; -1:error) = 0