2

我正在编写一个程序,该程序使用可变数量的线程将两个矩阵相乘,然后比较每次运行的执行时间。用户指定要使用的最大线程数,然后程序与 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);
}
4

2 回答 2

4

C++使用std::thread + std::bind

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)));
}
于 2012-11-01T08:04:13.937 回答
0

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

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)
    {
       ...
于 2012-11-01T13:08:07.977 回答