创建多个线程C ++

时间:2012-11-01 07:56:41

标签: c++ multithreading pthreads

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

2 个答案:

答案 0 :(得分:3)

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)));
}

答案 1 :(得分: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)
    {
       ...