【问题标题】:basic usage of pthread function with return value带返回值的 pthread 函数的基本用法
【发布时间】:2021-11-21 20:56:59
【问题描述】:

我正在尝试创建一个线程,当从 main.c 调用时可以读取文件中的行数

main.c

#include <stdio.h>
#define MAX_FILE_NAME 100
#include "t_func.h"
#include <pthread.h>
int main(){
    int linecount;
    pthread_t thread_id;
    FILE *fh = fopen("/home/usr154/out.log", "r");
    pthread_create(&thread_id, NULL, count_lines,&fh);
    pthread_join(thread_id, (void **) linecount);
    printf("lines: %d \n", linecount);
}

t_func.h

#include <stdlib.h>
#include <stdio.h>
int count_lines(int *fh){
    char c;
    int count =0;
    if (fh == NULL)
        {
            printf("Could not open file %s", fh);
            return 0;
        }
    for (c = getc(fh); c != EOF; c = getc(fh))
        if (c == '\n')
            count++;

    fclose(fh);
    return count;
}

我面临 2 个(或更多)问题,文件指针未被接受且返回值未被处理,非常感谢任何帮助(我是 C 编程新手)。

【问题讨论】:

  • pthread_create 中将&amp;fh 更改为fh。还将int *fh更改为void *arg,然后在函数内部添加FILE *fh = arg;
  • (void **) &amp;linecount致电pthread_join()
  • printf("Could not open file %s", fh); 不会编译,因为 fh 在您的代码中是 int *。如果您希望两者都传递一个结构,或者更好,请在 main() 或线程中进行打开的同一范围内进行错误检查。
  • 另外,隐含地提到,但你混淆了返回 int 的 open 和返回 FILE * 的 fopen。
  • "没有工作'没有帮助。你到底做了什么改变,确切的错误/问题是什么?正如其他 cmets 所指出的那样,你的代码中有很多错误。你修复了吗他们都?

标签: c pthreads


【解决方案1】:
  • 未使用 MAX_FILE_NAME。
  • 管理同一范围内的资源。我在这里选择在main() 中执行,在这种情况下包括fopen()、错误检查和fclose()
  • 更改了 *count_lines() 上的签名以匹配 pthread_create() 的预期。
  • 将 c 的类型从 char 更改为 int。
  • 更改了在命令行上获取文件的行为,以避免创建代码所需的文件。
  • 我收到一个警告 warning: cast to pointer from integer of different size 用于return (void *) count;gcc -Wall -Wextra。有没有更好的方法来返回值?除了全局变量之外,传入 arg 并带有值的 out 参数,或者在线程中分配一些东西。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void *count_lines(void *arg) {
    FILE *fh = (FILE *) arg;
    int c;
    int count = 0;
    while((c = getc(fh)) != EOF) {
        if(c == '\n') count++;
    }
    return (void *) count;
}

int main(int argc, char *argv[]) {
    pthread_t thread_id;
    if(argc != 2) {
        printf("usage: %s path_of_flie\n", argv[0]);
        return 1;
    }
    FILE *fh = fopen(argv[1], "r");
    if(!fh) {
        printf("Could not open file %s", argv[1]);
        return 1;
    }
    pthread_create(&thread_id, NULL, count_lines, fh);
    int linecount;
    pthread_join(thread_id, (void **) &linecount);
    fclose(fh);
    printf("lines: %d \n", linecount);
}

并在其自身上运行程序返回:

lines: 32

【讨论】:

  • 它有效,你能解释一下为什么你使用return (void *) count而不是return count吗?
  • pthread_create() 需要 void *(*start_routine) (void *) 类型,因此从不兼容的指针类型. If I declared void *count_files(void *arg) 中返回 void *. If you declare it returning and int and int I was getting warning passing 参数 3 的 'pthread_create' 但 return count然后我会收到警告returning ‘int’ from a function with return type ‘void *’ makes pointer from integer without a cast
猜你喜欢
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 2023-03-03
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多