简体   繁体   中英

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.

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) :

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM