我正在开发一个需要同时运行多个线程的项目。每个线程运行一个函数,该函数返回一个指向 int 数组的指针(转换为 void 指针)。例如,在线程运行的函数中,我想要的值存储如下:
void *func(void *args) {
int vals[3] = {0, 0, 0}, x = y = z = 0;
int *ptr = vals;
while(condition) {
.
.
.
ptr[0] += x;
ptr[1] += y;
ptr[2] += z;
}
return (void *) ptr;
}
在此函数结束时,ptr[0]、ptr[1] 和 ptr[2] 保存所需的值。这段代码只是为了让您了解发生了什么,我的实际实现没有任何问题。
我需要使用 pthread_join() 从每个线程获取各种值。每个线程处理一个文件,因此文件数 == 线程数 == 上述函数运行的次数。
我需要从每个线程获取 ptr[0]、ptr[1] 和 ptr[2] 的值,并在返回到 main 后将它们加在一起。这意味着如果有三个线程,那么我需要将线程 1 中的 ptr[0] 添加到线程 2 中的 ptr[0] 和线程 3 中的 ptr[0]。同样的事情也适用于 ptr[1] 和 ptr[2] 。然后我需要在最后打印 main 中的三个总计值。到目前为止,这就是我的做法,我的代码可以编译,但这些值是垃圾。
int main(int argc, char *argv[]) {
int NUM_THREADS = argc - 1;
int total1 = total2 = total3 = 0;
pthread_t *tids; /* Dynamically allocated array of pthreads */
void **vals; /* Stores the return values from each thread, this could be incorrect */
/*
** Some code where I allocate the arrays etc
*/
for (i= 0; i < NUM_THREADS; i++)
pthread_create(&tids[i], NULL, func, NULL);
for (i= 0; i < NUM_THREADS; i++)
pthread_join(tids[i], &(vals[i])); /* Again, this could be wrong */
for (i= 0; i < NUM_THREADS; i++) {
total1 += ((int*) vals[i])[0]; /* These statements very well could also be wrong */
total2 += ((int*) vals[i])[1];
total3 += ((int*) vals[i])[2];
}
/* Print totals */
return 0;
}
我知道每个线程中的值在 func 结束时都是正确的,但我不知道如何在 main 中正确存储、处理和打印它们。
此外,我使用的是 C90,无法使用任何其他版本的 C 的任何功能,并且我必须使用 pthread_join() 存储值。
最佳答案
Each thread runs a function that returns a pointer to an array of ints (cast as a void pointer). For example
void *func(void *args) { int vals[3] = {0, 0, 0}, x = y = z = 0; int *ptr = vals; ... return (void *) ptr; }
您应该首先修复函数以返回有意义的内容。按照目前的编写,该函数返回一个指向自动数组vals
的指针,该指针在函数返回后不再存在。
对返回指针的任何使用都会产生未定义的行为。
This code is just to give you an idea of whats happening, there is nothing wrong with my actual implementation.
有点难以置信。
pthread_join(tids[i], &(vals[i])); /* Again, this could be wrong */
这是错误的:vals
此时尚未初始化,因此您正在随机内存上写入。
I don't know how to properly store, process, and print them in main.
方法如下:
void *vals[NUM_THREADS];
..
for (i= 0; i < NUM_THREADS; i++) {
pthread_join(tids[i], &vals[i]);
}
for (i= 0; i < NUM_THREADS; i++) {
int *p = (int *)vals[i];
total1 += p[0];
total2 += p[1];
... etc.
}
关于c - 如何使用指针将从 Pthread 返回的多个数组存储在另一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59231699/