2

嗨,我正在尝试在 Mac 上的终端中运行此代码,它编译得很好,但是当我尝试执行它时出现段错误。当我运行 gdb 时,状态无效内存地址 000000 或类似的东西。有什么建议吗?先感谢您。

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


#define MAX_THREADS 512

void *compute_pi( void * );


int sample_points;
int total_hits;
int total_misses;
int hits[ MAX_THREADS ];
int sample_points;
int sample_points_per_thread;
int num_threads;



int main( int argc, char *argv[] )
{
  /* local variables */
  int ii;
  int retval;
  pthread_t p_threads[MAX_THREADS];
  pthread_attr_t attr;
  double computed_pi;

  /* initialize local variables */
  retval = 0;


  pthread_attr_init( &attr );
  pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM );

  /* parse command line arguments into sample points and number of threads */
  /* there is no error checking here!!!!! */
  sample_points = atoi(argv[1]);
  num_threads = atoi(argv[2]);

  /* uncomment this block if you want interactive input!!!! */
  /* if so...comment out the two statements above */
  /*  
  printf( "Enter number of sample points: " );
  scanf( "%d", &sample_points );
  printf( "Enter number of threads: " );
  scanf( "%d%", &num_threads );
  */

  total_hits = 0;
   sample_points_per_thread = sample_points / num_threads;

  for( ii=0; ii<num_threads; ii++ )
    {
      hits[ii] = ii;
      pthread_create( &p_threads[ ii ], &attr, compute_pi, (void *) &hits[ii] );
    }

  for( ii=0; ii<num_threads; ii++ )
    {
       pthread_join( p_threads[ ii ], NULL );
       total_hits += hits[ ii ];
    }

   computed_pi = 4.0 * (double) total_hits / ((double) (sample_points));


   printf( "Computed PI = %lf\n", computed_pi );


  /* return to calling environment */
  return( retval );
}


void *compute_pi( void *s )
{
  int seed;
  int ii;
  int *hit_pointer;
  int local_hits;
  double rand_no_x;
  double rand_no_y;

  hit_pointer = (int *) s;
  seed = *hit_pointer;
  local_hits = 0;

  for( ii=0; ii < sample_points_per_thread; ii++ )
    {
      rand_no_x = (double) (rand_r( &seed ))/(double)RAND_MAX;
      rand_no_y = (double) (rand_r( &seed ))/(double)RAND_MAX;
      if(((rand_no_x - 0.5) * (rand_no_x - 0.5) +
      (rand_no_y - 0.5) * (rand_no_y - 0.5)) < 0.25)
    local_hits++;
      seed *= ii;
    }

  *hit_pointer = local_hits;
  pthread_exit(0);
}
4

3 回答 3

1

如果我用 -ggdb 编译,在没有 cli 参数的 GDB 中运行程序,我发现段错误在 atoi 中。查看代码,我看到:

sample_points = atoi(argv[1]);
num_threads = atoi(argv[2]);

这不是通过检查argc来验证的,argv[1]并且argv[2]会在那里。

如果我使用此命令行运行:

 ./a.out 500 8

我得到这个结果:

  Computed PI = 2.616000

简而言之,我怀疑你运行的程序不正确,而且提供的不是很好。

于 2013-03-11T18:13:50.343 回答
0

您必须将两个参数传递给程序。这个程序不检查是否缺少参数是不好的。我会插入

if(argc<3){
    printf("Usage: %s [samples] [threads]\n",argv[0]);
    return 0;
}

sample_points = atoi(argv[1]);
于 2013-03-11T18:19:45.747 回答
0

除了不检查已经回答的 argc 的问题之外, atoi() 已被弃用,您应该考虑使用 strtol() 代替。

您系统上 atoi() 的手册页很可能也提到了这一点。

于 2013-03-12T10:46:36.920 回答