如何通过多个线程将矩阵提升到幂?

时间:2015-04-10 11:25:56

标签: c++ multithreading c++11 matrix stdthread

我正在尝试将矩阵提升到具有多个线程的幂,但我对线程不是很好。我也输入了键盘上的线程数,该数字在[1,矩阵高度]的范围内,然后我执行以下操作:

unsigned period = ceil((double)A.getHeight() / threadNum);
unsigned prev = 0, next = period;
for (unsigned i(0); i < threadNum; ++i) {
        threads.emplace_back(&power<long long>, std::ref(result), std::ref(A), std::ref(B), prev, next, p);

        if (next + period > A.getHeight()) {
            prev = next;
            next = A.getHeight();
        }
        else {
            prev = next;
            next += period;
        }
    }

我很容易将一个矩阵与另一个矩阵相乘多个线程,但问题是一旦完成1步,例如我需要将A提升到3的幂,A ^ 2就是那个步骤,在那一步之后我必须等待所有线程完成,然后继续做A ^ 2 * A.我怎样才能让我的线程等待呢?我正在使用std :: thread的。

在发布第一个回复后,我意识到我忘了提到我只想创建一次这些线程,而不是为每个乘法步骤重新创建它们。 < / p>

4 个答案:

答案 0 :(得分:2)

我建议使用condition_variable

算法将是这样的:

  1. 将N个部分的矩阵拆分为N个线程。

  2. 每个线程计算单个乘法所需的结果子矩阵。

  3. 然后使用threads_finished递增原子fetch_add计数器,并等待共享条件变量。

  4. 完成的最后一个线程(fetch_add()+ 1 ==线程计数),通知所有线程,它们现在可以继续处理。

  5. 利润。
  6. 编辑: 以下是如何停止线程的示例:

    #include <iostream>
    #include <thread>
    #include <mutex>
    #include <condition_variable>
    #include <vector>
    #include <algorithm>
    #include <atomic>
    
    void sync_threads(std::condition_variable & cv, std::mutex & mut, std::vector<int> & threads, const int idx) {
        std::unique_lock<std::mutex> lock(mut);
        threads[idx] = 1; 
        if(std::find(threads.begin(),threads.end(),0) == threads.end()) {
            for(auto & i: threads)
                i = 0;
            cv.notify_all();
        } else {
            while(threads[idx])
                cv.wait(lock);
        }
    }
    
    int main(){
    
        std::vector<std::thread> threads;
    
        std::mutex mut;
        std::condition_variable cv;
    
        int max_threads = 10;
        std::vector<int> thread_wait(max_threads,0);
    
        for(int i = 0; i < max_threads; i++) {
            threads.emplace_back([&,i](){
                    std::cout << "Thread "+ std::to_string(i)+" started\n";
                    sync_threads(cv,mut,thread_wait,i);
                    std::cout << "Continuing thread " + std::to_string(i) + "\n";
                    sync_threads(cv,mut,thread_wait,i);
                    std::cout << "Continuing thread for second time " + std::to_string(i) + "\n";
    
                });
        }
    
        for(auto & i: threads)
            i.join();
    }
    

    有趣的部分在这里:

    void sync_threads(std::condition_variable & cv, std::mutex & mut, std::vector<int> & threads, const int idx) {
        std::unique_lock<std::mutex> lock(mut); // Lock because we want to modify cv
        threads[idx] = 1; // Set my idx to 1, so we know we are sleeping
        if(std::find(threads.begin(),threads.end(),0) == threads.end()) {
            // I'm the last thread, wake up everyone
            for(auto & i: threads)
                i = 0;
            cv.notify_all();
        } else { //I'm not the last thread - sleep until all are finished
            while(threads[idx]) // In loop so, if we wake up unexpectedly, we go back to sleep. (Thanks for pointing that out Yakk)
                cv.wait(lock);
        }
    }
    

答案 1 :(得分:1)

这是mass_thread_pool

// launches n threads all doing task F with an index:
template<class F>
struct mass_thread_pool {
  F f;
  std::vector< std::thread > threads;
  std::condition_variable cv;
  std::mutex m;
  size_t task_id = 0;
  size_t finished_count = 0;
  std::unique_ptr<std::promise<void>> task_done;
  std::atomic<bool> finished;

  void task( F f, size_t n, size_t cur_task ) {
    //std::cout << "Thread " << n << " launched" << std::endl;
    do {
      f(n);
      std::unique_lock<std::mutex> lock(m);

      if (finished)
        break;

      ++finished_count;
      if (finished_count == threads.size())
      {
        //std::cout << "task set finished" << std::endl;
        task_done->set_value();
        finished_count = 0;
      }
      cv.wait(lock,[&]{if (finished) return true; if (cur_task == task_id) return false; cur_task=task_id; return true;});
    } while(!finished);
    //std::cout << finished << std::endl;
    //std::cout << "Thread " << n << " finished" << std::endl;
  }

  mass_thread_pool() = delete;
  mass_thread_pool(F fin):f(fin),finished(false) {}
  mass_thread_pool(mass_thread_pool&&)=delete; // address is party of identity

  std::future<void> kick( size_t n ) {
    //std::cout << "kicking " << n << " threads off.  Prior count is " << threads.size() << std::endl;
    std::future<void> r;
    {
      std::unique_lock<std::mutex> lock(m);
      ++task_id;
      task_done.reset( new std::promise<void>() );
      finished_count = 0;
      r = task_done->get_future();
      while (threads.size() < n) {
        size_t i = threads.size();
        threads.emplace_back( &mass_thread_pool::task, this, f, i, task_id );
      }
      //std::cout << "count is now " << threads.size() << std::endl;
    }
    cv.notify_all();
    return r;
  }
  ~mass_thread_pool() {
    //std::cout << "destroying thread pool" << std::endl;
    finished = true;
    cv.notify_all();
    for (auto&& t:threads) {
      //std::cout << "joining thread" << std::endl;
      t.join();
    }
    //std::cout << "destroyed thread pool" << std::endl;
  }
};

您使用任务构建它,然后您kick(77)启动该任务的77个副本(每个副本具有不同的索引)。

kick返回std::future<void>必须等待这个未来完成所有任务。

然后你可以销毁线程池,或者再次调用kick(77)来重新启动任务。

这个想法是你传递给mass_thread_pool的函数对象可以访问你的输入和输出数据(比如你想要乘法的矩阵,或指向它们的指针)。每个kick使它为每个索引调用一次函数。你负责将索引转换成任何偏移量。

Live example我使用它在另一个vector的条目中添加1。在迭代之间,我们交换向量。这会进行2000次迭代,并启动10个线程,并将lambda调用20000次。

注意auto&& pool = make_pool( lambda )位。需要使用auto&& - 因为线程池有自己的指针,我在大量线程池上禁用了move和copy构造。如果你真的需要传递它,请创建一个指向线程池的唯一指针。

我遇到了std::promise重置的一些问题,所以我把它包装在unique_ptr中。这可能不是必需的。

用于调试它的跟踪语句已被注释掉。

使用其他kick来呼叫n可能会也可能不会。绝对用较小的n调用它将不会按预期的方式工作(在这种情况下它会忽略n。)

在致电kick之前,不会进行任何处理。 kick是&#34;启动&#34;。

的缩写

...

如果您遇到问题,我要做的是制作一个拥有mass_thread_pool的多重对象。

乘数具有指向3个矩阵的指针(about)。 n个子任务中的每一个都生成out的一些子部分。

您将2个矩阵传递给乘数,它将指向out的指针设置为局部矩阵,ab指向传入的矩阵,执行kick ,然后等待,然后返回本地矩阵。

对于权力,你使用上面的乘数建立一个二次幂塔,同时根据指数的比特乘以累加到你的结果中(再次使用上面的乘数)。

上述版本的版本可能允许排队乘法和std::future<Matrix> s(以及未来矩阵的乘法)。

答案 2 :(得分:0)

我将从一个简单的分解开始:

  • 矩阵乘法获得多线程
  • 矩阵指数多次调用乘法。

类似的东西:

Mat multithreaded_multiply(Mat const& left, Mat const& right) {...}

Mat power(Mat const& M, int n)
{
    // Handle degenerate cases here (n = 0, 1)

    // Regular loop
    Mat intermediate = M;
    for (int i = 2; i <= n; ++i) 
    {
        intermediate = multithreaded_multiply(M, intermediate);
    }
}

在等待std::thread时,您拥有method join()

答案 3 :(得分:-1)

不是编程而是数学答案:对于每个方阵,都有一组所谓的“特征值”和“特征向量”,因此M * E_i = lambda_i * E_i。 M是矩阵,E_i是特征向量,lambda_i是特征值,它只是一个复数。所以M ^ n * E_i = lambda_i ^ n * E_i。因此,您只需要复数而不是矩阵的n次幂。特征向量是正交的,即任何向量V = sum_i a_i * E_i。所以M ^ n * V = sum_i a_i lambda ^ n E_i。 根据您的问题,这可能会显着加快速度。

相关问题