'Can pwrite in C be used to write file in parallel?
I am wondering when we are going to use pwrite to write a data to different locations with multiple threads. (I.e., Each thread writes a data to the single file but in different offset.)
Here is the sample code.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
char buf[50000000];
void *p_function(void * arg)
{
int s,e;
s = clock();
int* arr = (int*)arg;
int ret = pwrite(arr[0], buf, sizeof(buf), 100000000*arr[1]);
e = clock();
printf("Elapsed time : %d\n", e-s);
}
int main(void)
{
for(int i = 0; i < 50000000; i++) {
buf[i] = 5;
}
pthread_t pthread[3];
int thr_id;
int status;
int fd = open("File", O_RDWR);
int arg[3][2];
int thread_num = 3;
int s,e;
s = clock();
for(int i = 0; i < thread_num; i++) {
arg[i][1] = i;
arg[i][0] = fd;
pthread_create(&pthread[i], NULL, p_function, (void*)arg[i]);
}
for(int i = 0; i < thread_num; i++) {
pthread_join(pthread[i], (void **)&status);
}
e = clock();
printf("Elapsed time : %d", e-s);
return 0;
}
File
------------------------------------------------
| Location 1 | Location 2 | Location 3 |
------------------------------------------------
ㄴthread 1 ㄴthread 2 ㄴthread 3
With this code, I see there is no benefit of multithreading. (I expected that elapsed time is much faster than that of single thread, which is writing 150000000 bytes with one thread.)
Do I miss something?
Thank you in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
