Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
pth_monte_carlo_pi.c
//gcc 7.4.0 #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sys/time.h> int thread_count; pthread_mutex_t mutex; unsigned long long number_of_tosses; unsigned long long number_in_circle; void* Monte_Carlo(void* rank); int main(void) { struct timeval t; double start, finish, pi_estimate; long thread; pthread_t* thread_handles; //thread_count = strtol(argv[1], NULL, 10); thread_count = 2; printf("Enter the number of tosses:\n"); scanf("%llu", &number_of_tosses); number_in_circle = 0; pthread_mutex_init(&mutex, NULL); thread_handles = malloc(thread_count * sizeof(pthread_t)); gettimeofday(&t, NULL); start = t.tv_sec + t.tv_usec / 1000000.0; for(thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], NULL, Monte_Carlo, (void*) thread); } for(thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], NULL); } pi_estimate = 4 * number_in_circle / ((double) number_of_tosses); gettimeofday(&t, NULL); finish = t.tv_sec + t.tv_usec / 1000000.0; printf("Number in circle: %llu\n", number_in_circle); printf("Number of tosses: %llu\n", number_of_tosses); printf("The estimate of pi = %lf\n", pi_estimate); printf("The elapsed time = %e ms\n", (finish - start) * 1000); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; } void* Monte_Carlo(void* rank) { double x, y, distance_squared; long my_rank = (long) rank; unsigned long long toss; unsigned long long my_number_of_tosses = number_of_tosses / thread_count; unsigned long long my_number_in_circle = 0; for(toss = 0; toss < my_number_of_tosses; toss++) { x = ((double) rand_r(&my_rank)) / RAND_MAX * 2.0 - 1.0; y = ((double) rand_r(&my_rank)) / RAND_MAX * 2.0 - 1.0; distance_squared = x * x + y * y; if(distance_squared <= 1) { my_number_in_circle++; } } pthread_mutex_lock(&mutex); number_in_circle += my_number_in_circle; pthread_mutex_unlock(&mutex); return NULL; }
run
|
edit
|
history
|
help
1
18BCE2182 ASSESS_3 Q4
G
TeleBook2
c program for hollow rhombus
A_141110_Perfecto
A_141211_mayor
ACCES FUNC
22nd HW Switchv0.2
función free()
Finding the second largets value v0.8