/* parallelCopy.c */
#include "ds.h"
#include "kos/thread.h"
#define SIZE 4096
typedef struct PART{
unsigned long offset;
unsigned long size;
}part_t;
char file[50]; /* source file name */
char fileout[50]; /* target file name */
void* func1(void *arg){
printf("thread started\n");
int fin, fout, x, i;
i = 0;
part_t *part;
char data[SIZE];
part = (part_t *)arg;
if ((fin = fs_open(file, O_RDONLY)) == FILEHND_INVALID) ds_printf("Error open file");
if ((fout = fs_open(fileout, O_WRONLY)) == FILEHND_INVALID) ds_printf("Error open file");
lseek(fin, part->offset, SEEK_SET);
lseek(fout, part->offset, SEEK_SET);
while(i < part->size){
x = fs_read(fin, data, SIZE);
fs_write(fout, data, x);
i += x;
}
ds_printf("thread is done.\n");
fs_close(fout);
fs_close(fin);
return NULL;
}
int main(int argc, char *argv[]){
char data[SIZE];
struct stat f_stat;
int fin1, fout1, tmp, x, i = 0;
part_t part1, part2, part3;
kthread_t * t1, * t2; // two threads to share the load of main thread
if (thd_init(THD_MODE_COOP) != 0) ds_printf("Treads alredy initialized.");
if(argc < 3){
ds_printf("Not enough arguments.");
ds_printf("parallelCopy sourceFile targetFile");
return -1;
}
strcpy(file, argv[1]);
stat(file, &f_stat); // getting the meta info of file
strcpy(fileout, argv[2]);
ds_printf("Size of file is %lu \n", f_stat.st_size);
part1.offset = 0;
// dividing the size of file in 3 parts
part1.size = f_stat.st_size / 3;
part2.offset = part1.size;
part2.size = part1.size;
part3.offset = part2.offset + part2.size;
part3.size = f_stat.st_size - part3.offset;
/* creating part1 by main thread */
fin1 = fs_open(file, O_RDONLY);
fout1 = fs_open(fileout, O_WRONLY);
/*creating 3 threads to copy 2 n 3rd part of file */
if ((t1 = thd_create(0, func1, &part2)) == NULL) { ds_printf("Error create thread 1.");return CMD_ERROR;}
if ((t2 = thd_create(0, func1, &part3)) == NULL) { ds_printf("Error create thread 2.");return CMD_ERROR;}
while(i < part1.size){
x = fs_read(fin1, data, SIZE);
fs_write(fout1, data, x);
i += x;
}
if ((tmp=thd_join(t1, NULL)) !=0) { ds_printf("Error join thread 1. code: %d",tmp);return CMD_ERROR;} // making main to wait for t1
if ((tmp=thd_join(t2, NULL)) !=0) { ds_printf("Error join thread 2. code: %d",tmp);return CMD_ERROR;} // making main to wait for t2
ds_printf("file is copied");
fs_close(fout1);
fs_close(fin1);
return 0;
}