c - 多线程和读取文件

标签 c multithreading file

我编写了一个 C 代码来读取文件并使用多线程函数对其进行一些操作。我在 fun1 中读取文件,因此我希望该文件是线性读取的,但我对此代码所做的一些测试表明,该文件似乎没有按正确的顺序读取。我的代码有什么问题?!

#include <pthread.h>

#define BUFSIZE 1024*10
#define NUM_THREADS 4

typedef struct _thread_data_t {
  unsigned char id;
  char *msg;
  unsigned int msg_len;
} thread_data_t;

/* thread function */
void *thr_func(void *arg) {
  thread_data_t *data = (thread_data_t *)arg;
  fun2(data->msg, data->msg_len);
  pthread_exit(NULL);
}

void fun1(FILE *file) {
    unsigned char i, j, buf[BUFSIZE];
        pthread_t thr[NUM_THREADS];
        thread_data_t thr_data[NUM_THREADS];
        int rc, fr, fd = fileno(file);               
        for (;;) {
            for (i = 0; i < NUM_THREADS; i++) {
                fr = read(fd, buf, BUFSIZE);
                if (fr <= 0) break;
                thr_data[i].id = i;
                thr_data[i].msg = buf;
                thr_data[i].msg_len = fr;
                if ((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))) {
                    fprintf(stderr, "error: pthread_create, rc: %d\n", rc);
                    fr = -1;
                    break;
                }
            }    
            for (j = 0; j < i; j++) {
                pthread_join(thr[j], NULL);
            } 

            if (fr <= 0) break;
        }

}

编辑: 我认为在所有线程完成其工作之前,不会从文件中读取任何新内容。这是真的吗?

最佳答案

我认为你的问题是单个缓冲区:

buf[BUFSIZE];

在每个循环中,您将数据读入该缓冲区,然后为线程准备数据

thr_data[i].msg = buf;

我认为它不包括缓冲区本身的副本。我假设 msg 只是一个指针。

因此,在下一次迭代中,您将使用文件中的新数据覆盖 buf,从而更改已创建线程的数据。

我猜你需要

buf[NUM_THREADS][BUFSIZE];

这样每个线程都有自己的数据区域来工作。

引用:

I think that until all threads finish their works nothing new read from the file. Is it true?

正确,这就是 pthread_join 为您所做的事情

关于c - 多线程和读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34738683/

相关文章:

Python:如何将特定特征的文本添加到文本文件

c++ - 从具有不同变量类型的文件中逐行读取

vb.net 从 .txt 文件读取并显示内容

c - PIC(位置无关代码)

c中的消费者生产者问题

java - 如何在Spring TaskExecutor框架中管理线程

java - 使用 RentrantLock 实现生产者消费者时出现 IllegalMonitorStateException

c - C 中命令行参数 `argv` 的类型是什么?

c - 在 C 中使用转置的矩阵乘法

检查当前时间的数据结构,如果找到则删除?