2

This is my code using threads:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void *t1(void *arg)
{
    FILE *file = fopen((char *) arg, "w");

    for (long long int i = 0; i <= 100000000; i++) {
        fprintf(file, "--LINE-- <%lld>\n", i);
    }

    fclose(file);

    return NULL;
}

int main(int argc, char *argv[])
{
    pthread_t thread1, thread2, thread3, thread4;

    pthread_create(&thread1, NULL, t1, "FILE_1.txt");
    pthread_create(&thread2, NULL, t1, "FILE_2.txt");
    pthread_create(&thread3, NULL, t1, "FILE_3.txt");
    pthread_create(&thread4, NULL, t1, "FILE_4.txt");

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    pthread_join(thread3, NULL);
    pthread_join(thread4, NULL);

    return 0;
}

This is code without threads, I just call the function 4 times:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void *t1(void *arg)
{
    FILE *file = fopen((char *) arg, "w");

    for (long long int i = 0; i <= 100000000; i++) {
        fprintf(file, "--LINE-- <%lld>\n", i);
    }

    fclose(file);

    return NULL;
}

int main(int argc, char *argv[])
{
    t1("FILE_1.txt");
    t1("FILE_2.txt");
    t1("FILE_3.txt");
    t1("FILE_4.txt");

    return 0;
}

I get about the same time as with threads. (I used code to get the time however the question was being flagged as if it was asking how to get the time it takes to run a function so I had to remove it). Is this a problem with fprintf? How could I write to multiple files at the same time? Is there a better solution than using threads?

  • 1
    Get a faster drive. I/O to a physical device is serialized by the operating system, so threads trying to write at the same time just create contention, which slows things down. – J... May 17 '21 at 23:44
  • Does this answer your question? [Is it possible to use threads to speed up file reading?](https://stackoverflow.com/questions/3054442/is-it-possible-to-use-threads-to-speed-up-file-reading) – J... May 17 '21 at 23:45
  • It is also possible that `fprintf` is the bottleneck if an internal buffer is used to assemble some or all of the string to write. – 1201ProgramAlarm May 18 '21 at 00:31
  • @1201ProgramAlarm but it is not related to threads then and the title says "write to multiple files with threads". it doesnt mention speed and it doesnt correctly say "is it possible to write faster to files using threads" – muzzletov May 18 '21 at 01:23

0 Answers0