【发布时间】:2020-06-12 22:19:30
【问题描述】:
我正在编写一个应用程序,该应用程序使用不同的线程号运行 Monaco 算法,它们是 2、4、6 和 8 来计算 PI 的值。目标也是在使用更多线程时提高速度。问题是,我的代码不是分工,而是简单的做工2次!
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <math.h>
#include <string.h>
#define SEED 35791246
void *monaco(int arcg, char* argv) {
clock_t t1, t2;
float pi;
t1 = clock();
t2 = clock();
float diff = ((float)(t2 - t1) / 1000000.0F );
printf("\n");
printf("Thread number = %d\n", (int)(pthread_self()));
printf("Total Time: %f segundos\n", diff);
printf("\n");
printf("\n");
return 0;
}
void run_test(int num_thread) {
pthread_t pth_arr[num_thread];
int i = 0;
for (i = 0; i < num_thread; i++) {
pthread_create(&pth_arr[i], NULL, monaco, NULL);
}
for (i = 0; i < num_thread; i++) {
pthread_join(pth_arr[i], NULL);
}
}
int main(count) {
int num_thread = 9;
int pontos=20000;
double x,y;
count=0;
double z;
float pi;
int j = 0;
int i = 0;
srand(SEED);
count = 0;
for (i = 1; i < num_thread; i++) {
if (i==1)
{
continue;
}
if (i==3)
{
continue;
}
if (i==5)
{
continue;
}
if (i==7)
{
continue;
}
for (j = 0; j<pontos; j++) {
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
z = x*x+y*y;
if (z<=1) count++;
}
pi=(double)count/pontos * 4;
printf ("Points used are: %d , and the Pi estimate is: %g \n", pontos,pi);
printf ("Using %d threads.\n", i);
run_test(i);
}
return 0;
}
我得到的输出是:
Points used are: 20000 , and the Pi estimate is: 3.1288
Using 2 threads.
Thread number = -1332082944
Total Time: 0.000002 segundos
Thread number = -1340475648
Total Time: 0.000002 segundos
Thread number = -1340475648
Total Time: 0.000002 segundos
Points used are: 20000, and the Pi estimate is: 6.2932
Using 4 threads.
Thread number = -1332082944
Total time: 0.000002 segundos
Thread number = -1348868352
Total time: 0.000001 segundos
Thread number = -1357261056
Total time: 0.000001 segundos
Thread number = -1340475648
Total time: 0.000002 segundos
Points used are: 20000 , and the Pi estimate is: 9.4232
我怎样才能让它分工而不是做2次?
【问题讨论】:
标签: c multithreading for-loop pthreads