#include <pthread.h>
#include <stdio.h>
typedef struct {
int id;
char *filename;
float sum;
float dif;
} child;
void *calData(void *argv){
child *tempChild = (child *) argv;
FILE *fp;
int id = tempChild->id;
float max, min,buffer, sum , dif;
if(fopen(tempChild->filename, "r") == NULL) {
printf("Fail to open file");
exit(1);
}
fp = fopen(tempChild->filename, "r");
fscanf(fp, "%f", &buffer);
/* initialize the max and min */
max = buffer;
min = buffer;
/* scan every element in the dataset */
while(!feof(fp)) {
fscanf(fp, "%f", &buffer);
if(buffer <= min) {
min = buffer;
}
if(buffer >= max) {
max = buffer;
}
}
fclose(fp);
/* pass the calculted results to child */
sum = max + min;
dif = max - min;
tempChild->sum = sum;
tempChild->dif = dif;
printf("%.5f %.5f %.5f\n", sum, dif, id);
}
int main(int argc, char **argv){
/* initialize the of memory size of threads and children */
pthread_t *threads;
threads = (pthread_t *) malloc((argc-1) * sizeof(*threads));
child *children;
children = (child *) malloc((sizeof(child)) * (argc - 1));
int i, j;
/* start the threads */
for(i=0; i < (argc - 1); i++)
{
children[i].id = i;
children[i].filename = argv[i+1];
pthread_create(threads+i, NULL, calData, (void *)children+i);
}
/* Synchronize the completion of each thread. */
for(j=0; j < (argc-1); j++){
pthread_join(threads[j], NULL);
}
printf("%.5f %.5f \n",children[0].sum, children[0].dif);
}
你好,我正在学习 pthread。 这是问题,正如您可能在代码中看到的那样,输入应包含 3 个 txt 文件,我想处理它们并通过 pthread 获取 sum 和 dif。然而,一个输入参数没问题,但当我尝试输入 3 个数据文件时,它一直说“无法打开文件”。
我搜索过我可能需要一些有关互斥锁的帮助,谁能告诉我如何解决它?
最佳答案
这是明显的第一个问题:
pthread_create(threads+i, NULL, calData, (void *)children+i);
检查 C 中的操作优先级并将其替换为:
pthread_create(threads+i, NULL, calData, (void *)(children + i));
您的地址算术 +
运算符的优先级低于 (void *)
类型转换,因此 children
递增 i
字节而不是 i
child
结构大小。
但实际上,如果您的 C 编译器允许,我确实建议在您的情况下从指针切换到数组。更安全所以这是你的 main():
int main(int argc, char **argv){
pthread_t threads[argc -1];
child children[argc - 1];
int i, j;
/* start the threads */
for(i=0; i < (argc - 1); i++)
{
children[i].id = i;
children[i].filename = argv[i+1];
pthread_create(&threads[i], NULL, calData, &children[i]);
}
/* Synchronize the completion of each thread. */
for(j=0; j < (argc-1); j++){
pthread_join(threads[j], NULL);
}
printf("%.5f %.5f \n",children[0].sum, children[0].dif);
}
关于c - 多线程数据处理,如果多两个 argvs 总是会出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30969305/