1

我正在尝试使用 pthreads 添加两个矩阵。只是一个初学者程序,但我无法使用线程初始化矩阵。我的代码片段如下:

#include "test.h"

CvMat * matA;       /* first matrix */
CvMat * matB;       /* second matrix */
CvMat * matRes;     /* result matrix */

int size_x_a; /* this variable will be used for the first  dimension */
int size_y_a; /* this variable will be used for the second dimension */

int size_x_b,size_y_b;
int size_x_res;
int size_y_res;

int main()
{
/* assigining the values of sizes */
size_x_a = 200;
size_y_a = 200;
size_x_b = 200;
size_y_b = 200;

/* resultant matrix dimensions */
size_x_res = size_x_a;
size_y_res = size_y_b;

matA = cvCreateMat(size_x_a,size_y_a,CV_32SC1);
matB = cvCreateMat(size_x_b,size_y_b,CV_32SC1);
matRes = cvCreateMat(size_x_res,size_y_res,CV_32SC1);

pthread_t thread1;
pthread_t thread2;

int res1;
int res2;
 /*******************************************************************************/ 

    /*Creating a thread*/
res1 = pthread_create(&thread1,NULL,initializeA,(void*)matA);
if(res1!=0)
{
    perror("thread creation of thread1 failed");
    exit(EXIT_FAILURE);
}

for(int i =0;i<size_x_a;i++)
{
    for(int j = 0;j<size_y_a;j++)
    {
        printf("%d ",cvmGet(matA,i,j));
    }
}
    /*Creating a thread*/
res2 = pthread_create(&thread2,NULL,initializeB,(void*)matB);

if(res2!=0)
{
    perror("thread creation of thread2 failed");
    exit(EXIT_FAILURE);
}
return 0;
 }

void * initializeA(void * arg)
{
CvMat * matA  = (CvMat*)arg;
//matA = (CvMat*)malloc(size_x_a * sizeof(CvMat *));

/*initialiazing random values*/
for (int i = 0; i < size_x_a; i++) 
{
    for (int j = 0; j < size_y_a; j++) 
    {
        cvmSet(matA,i,j,size_y_a + j); 
    }
}
return 0;
}

void * initializeB(void * arg)
{
CvMat* matB  = (CvMat*)arg;
//matB = (CvMat*)malloc(size_x_b * sizeof(CvMat *));

/*initialiazing random values*/
for (int i = 0; i < size_x_b; i++) 
{
    for (int j = 0; j < size_y_b; j++) 
    {
      cvmSet(matB,i,j,size_y_b + j); 
    }
}
return 0;
}

我首先创建了两个线程来初始化 CvMat 矩阵。CvMat 矩阵是 opencv 的。初始化并调用 pthread_create 后,我试图访问 CvMat 的数据,但它崩溃了,这意味着它没有初始化。

请建议。

谢谢

4

1 回答 1

0

您显然必须等到初始化完成才能使用。

pthread_create(&thr1, ..., (void *)matA);
pthread_create(&thr2, ..., (void *)matB);

pthread_join(thr1, &result1);
pthread_join(thr2, &result2);

for (...) { ... cvmGet(matA,i,j); ... }

就目前而言,您正试图在初始化期间访问矩阵。

于 2012-07-06T06:58:22.627 回答