【问题标题】:Creating multiple threads C++创建多线程 C++
【发布时间】:2012-11-01 07:56:40
【问题描述】:

我正在编写一个程序,该程序使用可变数量的线程将两个矩阵相乘,然后比较每次运行的执行时间。用户指定要使用的最大线程数,然后程序与 1 个线程相乘,再次与 2、3、4.... 直到 max_threads(我们不必担心 max_threads 超过 8) .那么为每次运行创建线程的最佳方法是什么?这是我在黑暗中拍摄的最佳照片。

编辑:我必须使用 pthread。

//Ive already called multiplyMatrices for the single thread run. Start with 2 threads.
for (int h=2; h <= max_threads; h++)
{
    for(int i = 0; i < h; i++)
    {   
        pthread_create(thr_id[i],NULL, multiplyMatrices, i);
    }

    for(int i = 0; i < h; i++)
    {
        pthread_join(thr_id[i],NULL);
    }
}

multiplyMatrices 的代码如下。

void* multiplyMatrices(void* val)
{    
    for(int i = 0; i < n; i = i*val)
    {
        for(int j = 0; j < p; j++)
    {
            c[i][j] = 0;
            for(int k = 0; k < m; k++)
        {
                c[i][j] += matrix_A[i][k] * matrix_B[k][j];
            }
        }
    val++;
    }
    pthread_exit(0);
}

【问题讨论】:

  • 我建议自己研究一下 OpenMP。当你运行时,确保矩阵很好而且很大,否则你根本看不到任何改进。
  • 你为什么要计算 i*val?您意识到您将 i 乘以 地址,对吗?
  • 那么这段代码有什么问题呢?是不工作吗?你有错误吗?
  • 无法使用 OpenMP。我正在做 i*val 以便每个线程只处理某些行,使其可并行化(4 个线程-> 线程 0 执行第 0、4、8、12 行...线程 1 执行第 1、5、9、13 行。 ..)。不知道代码是否有问题,因为我还没有编译。我只是问这是否是做这样的事情的正确方法。
  • 对于codereview.stackexchange.com来说,这听起来像是一个更好的问题

标签: c++ multithreading pthreads


【解决方案1】:

使用std::thread+std::bindC++

std::vector<std::thread > thread_pool;
thread_pool.reserve(h);
void* someData;
for(int i = 0; i < h; i++)
{   
    thread_pool.push_back(std::thread(std::bind(multiplyMatrices, someData)));
}

【讨论】:

  • 既然std::thread 是(据我所知)一种只能移动的资源管理类型,那么这里需要std::unique_ptr 和动态内存分配吗?
  • 顺便说一句,这里不需要std::move,因为无论如何临时变量都是右值。
  • std::bind 这里不需要,你甚至可以直接使用emplace_back
【解决方案2】:

我在您的代码中看到的最大问题是您如何将数据传递给线程函数。数据应作为指针传递。以下应该会更好:

for (int h=2; h <= max_threads; h++)
{
    for(int i = 0; i < h; i++)
    {   
        // Notice Im passing a pointer to i here.
        // Since i may go out of scope, and its value could change before the
        // thread is started and multiplyMatrices() is called, this could be
        // risky. Consider using an array/vector defined before these for
        // loops to avoid this problem.
        pthread_create(thr_id[i],NULL, multiplyMatrices, &i);
        ...

void* multiplyMatrices(void* valPtr)
{    
    int val = *((int*) valPtr);
    for(int i = 0; i < n; i = i*val)
    {
       ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2019-06-24
    • 2023-03-20
    • 2023-03-15
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    相关资源
    最近更新 更多