草庐IT

c++ - 关于线程的问题

coder 2024-02-23 原文

我是线程编程的新手,我有一个概念上的问题。我正在做矩阵乘法作为我类(class)的一个项目。但是,我在不使用线程的情况下执行此操作,然后使用线程为答案矩阵的每个单元格计算标量积,然后再次将第一个矩阵分成多个比例,以便每个线程都有相等的部分要计算。我的问题是标量乘积实现完成得非常快,这是我所期望的,但是第三个实现并没有比非线程实现更快地计算出答案。例如,如果它使用 2 个线程,它会在大约一半的时间内完成计算,因为它可以同时处理矩阵的两半,但事实并非如此。我觉得第三个实现有问题,我不认为它是并行运行的,代码如下。谁能直接告诉我这个?并非所有代码都与问题相关,但我将其包括在内以防问题不是本地的。 谢谢,

主程序:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include<fstream>
#include<string>
#include<sstream>

#include <matrix.h>
#include <timer.h>
#include <random_generator2.h>

const float averager=2.0; //used to find the average of the time taken to multiply the matrices.

//Precondition: The matrix has been manipulated in some way and is ready to output the statistics
//Outputs the size of the matrix along with the user elapsed time.
//Postconidition: The stats are outputted to the file that is specified with the number of threads used
//file name example: "Nonparrallel2.dat"
void output(string file, int numThreads , long double time, int n);

//argv[1] = the size of the matrix
//argv[2] = the number of threads to be used.
//argv[3] = 
int main(int argc, char* argv[])
{ 
  random_generator rg;
  timer t, nonparallel, scalar, variant;
  int n, total = 0, numThreads = 0;
  long double totalNonP = 0, totalScalar = 0, totalVar = 0;

  n = 100;

/*
 * check arguments
 */
      n = atoi(argv[1]);
      n = (n < 1) ? 1 : n;
      numThreads = atoi(argv[2]);
/*
 * allocated and generate random strings
 */
  int** C;
  int** A;
  int** B;

  cout << "**NOW STARTING ANALYSIS FOR " << n << " X " << n << " MATRICES WITH " << numThreads << "!**"<< endl;

  for (int timesThrough = 0; timesThrough < averager; timesThrough++)
  {

      cout << "Creating the matrices." << endl;
      t.start();
      C = create_matrix(n);
      A = create_random_matrix(n, rg);
      B = create_random_matrix(n, rg);
      t.stop();

      cout << "Timer (generate): " << t << endl;

        //---------------------------------------------------------Ends non parallel-----------------------------
        /*
         * run algorithms
         */
          cout << "Running non-parallel matrix multiplication: " << endl;
          nonparallel.start();
          multiply(C, A, B, n);
          nonparallel.stop();
        //-----------------------------------------Ends non parallel----------------------------------------------


        //cout << "The correct matrix" <<endl;
        //output_matrix(C, n);

          cout << "Timer (multiplication): " << nonparallel << endl;
          totalNonP += nonparallel.user();


          //D is the transpose of B so that the p_scalarproduct function does not have to be rewritten
          int** D = create_matrix(n); 
          for (int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                D[i][j] = B[j][i];
        //---------------------------------------------------Start Threaded Scalar Poduct--------------------------
          cout << "Running scalar product in parallel" << endl;
          scalar.start();
          //Does the scalar product in parallel to multiply the two matrices.
          for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++){
            C[i][j] = 0;
            C[i][j] = p_scalarproduct(A[i],D[j],n,numThreads);
            }//ends the for loop with j
          scalar.stop();

          cout << "Timer (scalar product in parallel): " << scalar << endl;
          totalScalar += scalar.user();
        //---------------------------------------------------Ends Threaded Scalar Poduct------------------------


        //---------------------------------------------------Starts Threaded Variant For Loop---------------
           cout << "Running the variation on the for loop." << endl;
            boost :: thread** thrds;


            //create threads and bind to p_variantforloop_t
            thrds = new boost::thread*[numThreads];

            variant.start();
            for (int i = 1; i <= numThreads; i++)
                thrds[i-1] = new boost::thread(boost::bind(&p_variantforloop_t, 
                        C, A, B, ((i)*n - n)/numThreads ,(i * n)/numThreads, numThreads, n));   
cout << "before join" <<endl;
            // join threads 
              for (int i = 0; i < numThreads; i++)
            thrds[i]->join();
             variant.stop();

            // cleanup 
              for (int i = 0; i < numThreads; i++)
            delete thrds[i];
              delete[] thrds;

        cout << "Timer (variation of for loop): " << variant <<endl;
        totalVar += variant.user();
        //---------------------------------------------------Ends Threaded Variant For Loop------------------------

         // output_matrix(A, n);
         // output_matrix(B, n);
         //   output_matrix(E,n);

        /*
         * free allocated storage
         */

        cout << "Deleting Storage" <<endl;

          delete_matrix(A, n);
          delete_matrix(B, n);
          delete_matrix(C, n);
          delete_matrix(D, n);  

        //avoids dangling pointers
          A = NULL;
          B = NULL;
          C = NULL;
          D = NULL;
  }//ends the timesThrough for loop   

  //output the results to .dat files
  output("Nonparallel", numThreads, (totalNonP / averager) , n);
  output("Scalar", numThreads, (totalScalar / averager), n);
  output("Variant", numThreads, (totalVar / averager), n);

  cout << "Nonparallel = " << (totalNonP / averager) << endl;
  cout << "Scalar = " << (totalScalar / averager) << endl;
  cout << "Variant = " << (totalVar / averager) << endl;

  return 0;
}

void output(string file, int numThreads , long double time, int n)
{
    ofstream dataFile;
    stringstream ss;

    ss << numThreads;
    file += ss.str();
    file += ".dat";

    dataFile.open(file.c_str(), ios::app);
    if(dataFile.fail())
    {
        cout << "The output file didn't open." << endl;
        exit(1);
    }//ends the if statement.
    dataFile << n << "     " << time << endl;
    dataFile.close();
}//ends optimalOutput function

矩阵文件:

#include <matrix.h>
#include <stdlib.h>

using namespace std;

int** create_matrix(int n)
{
  int** matrix;

  if (n < 1) 
    return 0;

  matrix = new int*[n];
  for (int i = 0; i < n; i++)
    matrix[i] = new int[n];

  return matrix;
}

int** create_random_matrix(int n, random_generator& rg)
{
  int** matrix;

  if (n < 1) 
    return 0;

  matrix = new int*[n];
  for (int i = 0; i < n; i++)
    {
      matrix[i] = new int[n];
      for (int j = 0; j < n; j++)
    //rg >> matrix[i][j];
    matrix[i][j] = rand() % 100;
    }

  return matrix;
}

void delete_matrix(int** matrix, int n)
{ 
    for (int i = 0; i < n; i++) 
      delete[] matrix[i];

    delete[] matrix;

    //avoids dangling pointers.
    matrix = NULL;
}

/*
 * non-parallel matrix multiplication
 */
void multiply(int** C, int** A, int** B, int n)
{ 
  if ((C == A) || (C == B))
    { 
      cout << "ERROR: C equals A or B!" << endl;
      return;
    }

  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      {
    C[i][j] = 0;
    for (int k = 0; k < n; k++)
      C[i][j] += A[i][k] * B[k][j];
     }
} 

void p_scalarproduct_t(int* c, int* a, int* b, 
                   int s, int e, boost::mutex* lock)
{ 
  int tmp;

  tmp = 0;
  for (int k = s; k < e; k++){
    tmp += a[k] * b[k];
//cout << "a[k]= "<<a[k]<<"b[k]= "<< b[k] <<"    "<<k<<endl;
}
  lock->lock();
  *c = *c + tmp;
  lock->unlock();
} 

int p_scalarproduct(int* a, int* b, int n, int m)
{ 
  int c;
  boost::mutex lock;
  boost::thread** thrds;

  c = 0;

/* create threads and bind to p_merge_sort_t */
  thrds = new boost::thread*[m];
  for (int i = 0; i < m; i++)
    thrds[i] = new boost::thread(boost::bind(&p_scalarproduct_t, 
                             &c, a, b, i*n/m, (i+1)*n/m, &lock));
/* join threads */
  for (int i = 0; i < m; i++)
    thrds[i]->join();

/* cleanup */
  for (int i = 0; i < m; i++)
    delete thrds[i];
  delete[] thrds;

  return c;
} 

void output_matrix(int** matrix, int n)
{ 
  cout << "[";
  for (int i = 0; i < n; i++)
    {
      cout << "[ ";
      for (int j = 0; j < n; j++)
    cout << matrix[i][j] << " ";
      cout << "]" << endl;
    }
  cout << "]" << endl;
}





void p_variantforloop_t(int** C, int** A, int** B, int s, int e, int numThreads, int n)
{
//cout << "s= " <<s<<endl<< "e= " << e << endl;
    for(int i = s; i < e; i++)
        for(int j = 0; j < n; j++){
          C[i][j] = 0;
//cout << "i " << i << "  j " << j << endl;
          for (int k = 0; k < n; k++){
            C[i][j] += A[i][k] * B[k][j];}
        }
}//ends the function

最佳答案

我猜你遇到了 False Sharing .尝试在 p_variantforloop_t 中使用局部变量:

void p_variantforloop_t(int** C, int** A, int** B, int s, int e, int numThreads, int n)
{
    for(int i = s; i < e; i++)
        for(int j = 0; j < n; j++){
          int accu = 0;
          for (int k = 0; k < n; k++)
            accu += A[i][k] * B[k][j];
          C[i][j] = accu;
        }
}

关于c++ - 关于线程的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5850757/

有关c++ - 关于线程的问题的更多相关文章

  1. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  4. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  5. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  6. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  7. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. ruby-on-rails - 简单的 Ruby on Rails 问题——如何将评论附加到用户和文章? - 2

    我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。

  10. 【高数】用拉格朗日中值定理解决极限问题 - 2

    首先回顾一下拉格朗日定理的内容:函数f(x)是在闭区间[a,b]上连续、开区间(a,b)上可导的函数,那么至少存在一个,使得:通过这个表达式我们可以知道,f(x)是函数的主体,a和b可以看作是主体函数f(x)中所取的两个值。那么可以有,  也就意味着我们可以用来替换 这种替换可以用在求某些多项式差的极限中。方法: 外层函数f(x)是一致的,并且h(x)和g(x)是等价无穷小。此时,利用拉格朗日定理,将原式替换为 ,再进行求解,往往会省去复合函数求极限的很多麻烦。使用要注意:1.要先找到主体函数f(x),即外层函数必须相同。2.f(x)找到后,复合部分是等价无穷小。3.要满足作差的形式。如果是加

随机推荐