让多个线程同时读取一个文件的最佳方法是什么?
例如,如果我告诉我的程序用4个线程运行,并且文件有12个字符长,我希望每个线程同时读取3个字符。
这就是我目前所拥有的:
线程函数:
void *thread(void *arg) {
// can't seem to find the right solution to make it work here...
}
主函数(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;
}
}
我想给线程函数一个带index的struct来开始读取,index来停止读取,但它确实很混乱,我似乎找不到正确的解决方案。
最佳答案
假设你有一个类似的结构:
struct ft
{
char* file_name;
int start_index;
int end_index;
};
然后在你的线程中:
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
}
}
另外,不要忘记在主线程中执行
pthread_join
,这将使它等待其他线程完成。