[英]What is the best way to have multiple threads read a file at the same time?
What is the best way to have multiple threads read a file at the same time ?让多个线程同时读取文件的最佳方法是什么?
For example, if I tell my program to run with 4 threads and the file is 12 characters long, I want each thread to read 3 chars at the same time.例如,如果我告诉我的程序用 4 个线程运行并且文件长 12 个字符,我希望每个线程同时读取 3 个字符。
This is what I have so far :这是我到目前为止:
thread function :线程函数:
void *thread(void *arg) {
// can't seem to find the right solution to make it work here...
}
main function (thread_count is the number of threads and text_size the size of text) : main 函数(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;
}
}
I was thinking of giving to the thread function a struct with index to start reading and index to stop reading, but it's really confusing and I can't seem to find the right solution.我想给线程函数一个结构体,它带有开始读取的索引和停止读取的索引,但这真的很令人困惑,我似乎找不到正确的解决方案。
Assuming you have a struct like:假设你有一个像这样的结构:
struct ft
{
char* file_name;
int start_index;
int end_index;
};
Then in your thread:然后在你的线程中:
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
}
}
Also, don't forget to do pthread_join
in your main thread, which will make it wait for the other threads to finish.另外,不要忘记在主线程中执行pthread_join
,这将使其等待其他线程完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.