Неверное преобразование int в unsigned int

Этот код дается для назначения. Тем не менее, с ошибкой в ​​функции compute pi monte carlo есть ошибка. недопустимая статистика ошибок преобразования из int в unsigned int. Я не уверен, если это было задумано, но я не смог исправить эту проблему. Эта функция является частью примера работы с потоками на случай, если вам интересно. Любые предложения приветствуются

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;//*error is these lines
rand_no_y = (double) (rand_r( &seed ))/(double)RAND_MAX;//*error is these lines
if(((rand_no_x - 0.5) * (rand_no_x - 0.5) +
(rand_no_y - 0.5) * (rand_no_y - 0.5)) < 0.25)//*error
local_hits++;
seed *= ii;
}

*hit_pointer = local_hits;
pthread_exit(0);
}

я сделал некоторую отладку и теперь вижу, где ошибка может быть расположена. заболел теперь основной функцией, где вызывается вычисление пи. Я считаю, что именно здесь аргументы разбираются на точки выборки и количество потоков. Когда я запускаю программу, она запрашивает ввод, после чего происходит сбой из-за ошибки сегментации. Какие-либо предложения?

  #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_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 );

printf( "Enter number of sample points: " );
scanf( "%d", &sample_points );
printf( "Enter number of threads: " );
scanf( "%d%", &num_threads );

/* 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]);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 );
}

0

Решение

От rand_r(3) справочная страница:

int
rand_r(unsigned *ctx);

Как видите, это занимает unsigned указатель — если вы передадите int и у вас есть соответствующие предупреждения / ошибки включены в вашем компиляторе (и кажется, что вы делаете), вы получите эту ошибку. Изменить тип seed и вы будете установлены.

1

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]