【发布时间】:2021-04-24 04:50:43
【问题描述】:
我这样声明我的线程:
for (thread_num = 0; thread_num < NUM_THREADS; thread_num++) //for each thread do
pthread_create(&thread_handles[thread_num], NULL, gemver_default, (void*)thread_num); //create and run the thread. The thread will run the gemver_default. The thread_num will be passed as input to the gemver_default().
for (thread_num = 0; thread_num < NUM_THREADS; thread_num++) //for each thread do
pthread_join(thread_handles[thread_num], NULL); //wait for the thread to finish
然后是我的 pthread 循环:
unsigned short int gemver_default(void * thread_num) {
long int my_thread_num = (long int)thread_num; //store the input of the function to my_thread_num
int local = P / NUM_THREADS; //the number of array elements that each thread must compute their sqrt
int starting_element = my_thread_num * local; //first array element to be computed by this thread
int ending_element = starting_element + local - 1; //last array element to be computed by this thread
for (i = starting_element; i < ending_element; i++)
for (j = 0; j < local; j++)
A2[i][j] += u1[i] * v1[j] + u2[i] * v2[j];
}
然后是我原来的循环:
unsigned short int gemver_default() {
//this is the loop to parallelize
for (int i = 0; i < P; i++)
for (int j = 0; j < P; j++)
A2[i][j] += u1[i] * v1[j] + u2[i] * v2[j];
return 0;
}
我不明白为什么输出不同?
我已经创建了线程,引用了我想要处理的函数,并将其实现到我的旧循环中。
【问题讨论】:
-
您是否已初始化所有变量?我不会问,但既然你还没有发布minimal reproducible example,我不得不问。 (例如
A2是如何创建的,即int **A2 = NULL;, thenmalloc'd` 一些内存,或intA2[X][Y];。这些都是未初始化变量的示例。)
标签: arrays c parallel-processing pthreads 2d