c - 如何使用 C 线程从头到尾读取文件?

标签 c multithreading pthreads

我需要用2个线程读取一个文件,其中一个将从头到中读取文件,另一个将从头到中读取文件。我的文件中有 10 个 float 。前 5 个 float 将由一个线程求和,最后 5 个 float 将由另一个线程求和。 func1 没问题,但我无法处理 func2 部分。

float sum=0,sum1=0,sum2=0,flo;  
int i=0;
FILE *fp;

 void *func1(void *param) {
      for(i=1;i<=5;i++) {
      fscanf(fp,"%f",&flo);
      sum1=flo+sum1;
}
      pthread_exit(0);
}
int main() {

   pthread_t tid;   
   pthread_attr_t attr;   
   pthread_attr_init(&attr);

   fp = fopen("input.txt","r");
   pthread_create(&tid, &attr, func1,fp);
   pthread_create(&tid, &attr, func2,fp);
   pthread_join(tid, NULL);
}

最佳答案

到目前为止,最简单的技术是使用单个线程来进行读取。但是,鉴于这是使用 POSIX 线程的练习,那么:

  • 您应该始终检查 fscanf() 的返回值 — 线程或无线程。
  • 即使在非线程程序中,您也应该避免使用全局变量。
  • 由于线程以及 isum1flo 都是全局的,因此您正在为可怕的竞争条件做好准备。您应该使用互斥体来防止并发访问这些变量。或者,更好的是,让它们全部位于线程函数的本地。
  • 您还需要让函数返回适当的值。
  • 您应该使用传递给线程函数的参数。
  • 您应该将线程 ID 值保存在单独的变量中,以便可以等待两个线程完成;您的代码仅等待一个线程完成(第二个线程)。
  • 您应该打印结果。
  • 您不必担心文件流上的同步 - POSIX 要求无论如何都要进行同步(请参阅 flockfile() 及其近亲都记录在同一页上)。
  • 您应该同时提供 func1()func2() 来创建 MCVE ( Minimal, Complete, Verifiable Example 。我假设相同的函数适用于两个线程,这在上下文中并不是一个有风险的假设。

将它们放在一起会导致:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

struct tcb
{
    FILE *fp;
    double sum;
    int thread_num;
};

static void *func1(void *param)
{
    struct tcb *tcb = param;
    double sum1 = 0.0, flo;
    for (int i = 1; i <= 5; i++)
    {
        if (fscanf(tcb->fp, "%lf", &flo) != 1)
        {
            fprintf(stderr, "Thread %d failed to read value %d\n", tcb->thread_num, i);
            pthread_exit(0);
        }
        sum1 += flo;
    }
    tcb->sum = sum1;
    pthread_exit(0);
}

int main(void)
{
    FILE *fp;
    pthread_t tid1;
    pthread_t tid2;
    struct tcb tcb[2];
    pthread_attr_t attr;

    pthread_attr_init(&attr);
    const char *filename = "input.txt";

    if ((fp = fopen(filename, "r")) == NULL)
    {
        fprintf(stderr, "Failed to open file %s for reading\n", filename);
        exit(1);
    }
    tcb[0].fp = fp;
    tcb[0].thread_num = 0;
    tcb[0].sum = 0.0;
    tcb[1].fp = fp;
    tcb[1].thread_num = 1;
    tcb[1].sum = 0.0;
    pthread_create(&tid1, &attr, func1, &tcb[0]);
    pthread_create(&tid2, &attr, func1, &tcb[1]);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    printf("Total from thread 0 = %f\n", tcb[0].sum);
    printf("Total from thread 1 = %f\n", tcb[1].sum);
    printf("Grand total         = %f\n", tcb[0].sum + tcb[1].sum);
    return 0;
}

还有其他方法可以处理线程函数的输入和输出,但创建一个简单的结构似乎非常简单和合适。

给定数据文件(input.txt):

 23.192048
  4.128715
  3.465737
 74.307105
  4.329846
  6.098813
  9.497566
  6.988740
 11.530497
 53.262049
  9.469198
 41.305744

一次运行的输出是:

Total from thread 0 = 87.377665
Total from thread 1 = 109.423451
Grand total         = 196.801116

其他运行给出了不同的值(另一次运行颠倒了两个结果)。这两个和对应于数据文件(有 12 行)的第 6-10 行和 1-5 行。这表明一个线程设法获得调度并读取其数据配额,然后让另一个线程读取下一个数据配额。添加更多线程(使用循环和线程 ID 值数组)和更多数据可能会显示不同的 I/O 操作交错顺序。

关于c - 如何使用 C 线程从头到尾读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55912085/

相关文章:

c - pthread 指针数组

找不到 -lpthread?

c# - 寻找一种允许一个编写器并拒绝其他编写器的框架类

c - 如何调试gdb中的sem_wait函数?

c++ - Win32 API - 将 LO/HIWORD 转换为 HANDLE

可以从共享内存创建 Tensorflow 变量吗?

Java并行编程

c++ - GCC 8.3 + Linux 上的 boost::thread_specific_ptr 的 Valgrind 错误

c - Windows DLL 文件的正确构建模式是什么?

c - 我的 C 程序给出了相同的计算结果