什么是让多个线程同时读取文件的最佳方法?
例如,如果我告诉我的程序使用4个线程运行,并且文件长度为12个字符,则我希望每个线程同时读取3个字符。
以下是我目前的内容:
线程函数:
我正在考虑给线程函数提供一个结构体,其中包含开始读取的索引和停止读取的索引,但这确实很令人困惑,我似乎找不到正确的解决方案。
例如,如果我告诉我的程序使用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;
}
}
我正在考虑给线程函数提供一个结构体,其中包含开始读取的索引和停止读取的索引,但这确实很令人困惑,我似乎找不到正确的解决方案。
pthread_create
。该函数(start_routine
)将需要将参数(arg
)转换为指向你的结构体的指针,然后执行自己的工作(查找、读取、关闭)。基本上,你可以通过该参数向线程提供上下文。 - Adam Kotwasinskipread
。 - user253751