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?