我编写了一个 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/