使用蒙特卡洛模拟多线程计算 Pi

标签 c multithreading

因此,我目前正在使用蒙特卡洛模拟来计算 Pi。我目前有 5 种不同的场景:500、20000、100000、1000000、10000000 点来计算 Pi,我的问题是我必须对算法进行多线程处理(每个点数有 2、4、6 和 8 个线程)但我已经一直在寻找多线程,无法理解为了实现我的目标我必须做什么。 希望有人可以向我解释或向我展示如何实际执行该算法的多线程部分。

代码看起来像这样:

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


int main () 
{

 int circ, total, i;
 double a, x, y, pi;

 a = 0;
 i = 0;

 total = 500;
 circ = 0;
 for ( i = 0; i<total; i++ ) {
  x = (double)rand ()/ RAND_MAX;
  y = (double)rand ()/ RAND_MAX;
  a = x*x + y*y
  if (a<=1) circ ++;
  }
 pi = (double)circ/total * 4;
 printf ("For %d points, pi is %g \n", total, pi);

 total = 20000;
 circ = 0;
 for ( i = 0; i<total; i++ ) {
  x = (double)rand ()/ RAND_MAX;
  y = (double)rand ()/ RAND_MAX;
  a = x*x + y*y
  if (a<=1) circ ++;
  }
 pi = (double)circ/total * 4;
 printf ("For %d points, pi is %g \n", total, pi);


 total = 100000;
 circ = 0;
 for ( i = 0; i<total; i++ ) {
  x = (double)rand ()/ RAND_MAX;
  y = (double)rand ()/ RAND_MAX;
  a = x*x + y*y
  if (a<=1) circ ++;
  }
 pi = (double)circ/total * 4;
 printf ("For %d points, pi is %g \n", total, pi);


 total = 1000000;
 circ = 0;
 for ( i = 0; i<total; i++ ) {
  x = (double)rand ()/ RAND_MAX;
  y = (double)rand ()/ RAND_MAX;
  a = x*x + y*y
  if (a<=1) circ ++;
  }
 pi = (double)circ/total * 4;
 printf ("For %d points, pi is %g \n", total, pi);

 total = 10000000;
 circ = 0;
 for ( i = 0; i<total; i++ ) {
  x = (double)rand ()/ RAND_MAX;
  y = (double)rand ()/ RAND_MAX;
  a = x*x + y*y
  if (a<=1) circ ++;
  }
 pi = (double)circ/total * 4;
 printf ("For %d points, pi is %g \n", total, pi);

非常感谢您的耐心等待,祝您有愉快的一天:)

最佳答案

编写程序或算法的多线程版本时,首先要考虑的是

  1. 您必须首先确定您的应用程序的哪些部分 享受多线程或需要并行运行。哪个是为了 循环你的代码部分

  2. 您希望并行化的代码部分或分支必须
    彼此独立,以避免诸如竞争条件之类的事情。和 从您的代码中可以看出, 享受多线程的潜在代码分支在这里 条件。

    a = x * x + y * y; if ( a <= 1 ) circ++;

    如果你想出这个代码的多线程版本,你将不得不处理诸如竞争条件之类的事情,因为所有线程都想同时写入 a。共享内存。即使您尝试让每个线程专门写入共享内存,您最终可能会遇到另一个问题,这可能是您代码的串行版本比并行版本快得多,其原因可能是线程有循环很长时间持有一个锁,阻止其他线程访问 a共享内存。尝试使用无锁机制(例如原子)也会导致内存排序等问题

你应该做什么

你现在应该做的是以某种方式重新设计你的代码,循环将没有任何依赖性,或者如果你准备好面对多线程的危险而不重新设计你的代码,你可以看看这本书,它有一个用于学习 pthreads 和 omp 的部分。这是一本不错的书,但大多数示例无法编译取决于您使用的是哪种 c 标准编译

Darryl Gove - Multicore Application Programming for Windows, Linux, and Oracle Solaris - 2010

关于使用蒙特卡洛模拟多线程计算 Pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428576/

相关文章:

c - 实现 strcpy : what if the destination is shorter than the source?

java - 如何在任何一个线程完成后终止所有其他正在运行的线程

c++ - 是否还需要在源文件中添加 'extern C' ?

C程序编译但不执行

编译器错误消息定制

c++ - 错误 C2248 : strange error when I use thread

c# - 没有锁的线程安全集合

c - 如何获取 "how many and which symbols are resolved by linker"的信息?

java - 如何添加Java多线程

java - 只要 protected ,私有(private)最终 String[] 数组就线程安全吗?