-1

我的程序需要创建一些线程,但我被困在 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);
  }

}
4

2 回答 2

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
于 2014-11-07T00:31:30.880 回答
0
safe = pthread_join( tids[i], (void **)&resultado ) ;
printf("%d", error );
if ( safe != 0 )     // Error here
    perror ("Error waiting");

如果像大多数调用那样将错误隐藏pthread_join在. 如果要调用打印错误,则需要在生成错误的函数返回后立即调用它。errnoprintfpthread_joinperror

但是,pthread_join不会将错误隐藏在 中errno,它会返回错误。所以打电话是perror不行的。你可以这样做:

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

或者

if ( safe != 0 )
    printf ("Error waiting: %s\n", strerror (safe));
于 2014-11-06T23:20:22.003 回答