让多个线程同时读取文件的最佳方法是什么?

Pau*_*and 5 c multithreading file pthreads

让多个线程同时读取文件的最佳方法是什么?

例如,如果我告诉我的程序使用 4 个线程运行,并且文件有 12 个字符长,我希望每个线程同时读取 3 个字符。

这是我到目前为止所拥有的:

线程函数:

void *thread(void *arg) {
    // can't seem to find the right solution to make it work here...
}
Run Code Online (Sandbox Code Playgroud)

main 函数(thread_count 是线程数,text_size 是文本大小):

// Number of characters each thread should read
uint16_t thread_chars_num = (text_size / thread_count);

pthread_t threads[thread_count];
for (int i = 0; i < thread_count; i++) {
    if(i == thread_count - 1) { // last thread might have more work
        thread_chars_num += (text_size % thread_count )
    }
    if (pthread_create(&threads[i], NULL, thread, &thread_chars_num) != 0) {
        fprintf(stderr, "pthread_create failed!\n");
      return EXIT_FAILURE;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在考虑给线程函数一个带有开始读取索引和停止读取索引的结构,但这真的很令人困惑,我似乎找不到正确的解决方案。

mni*_*tic 4

假设您有一个类似的结构:

struct ft 
{
    char* file_name;
    int start_index;
    int end_index;
};
Run Code Online (Sandbox Code Playgroud)

然后在你的线程中:

void *thread(void *arg) {
    int i;
    int c;
    struct ft* fi = (struct ft*)arg;
    FILE* file = fopen(fi->file_name);
    fseek (file , fi->start_index, SEEK_SET);
    for(i = 0; i < fi->end_index - fi->start_index; i++)
    {
        c = getc(file);
        //do something
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记pthread_join在主线程中执行此操作,这将使其等待其他线程完成。