I want to have >= 2 threads (but for the time being let's just say we have 2) that reads from separate files corresponding to each thread into a buffer, then write the buffer into the same file alternatingly.
Normally, one would do it in this way: get thread A to read the file A, memorize the byte position of where it left off, write to sameFile.txt,memorize where it left off and then get thread B to read file B, memorize the byte position of where it left off, then continue from where A left, write to sameFile.txt.
However, I am asking is it possible to capitalize on certain "inherit nature" of C++ file stream operations and reliably perform the above task WITHOUT calling "navigation" functions like seekg, seekp?
I'm having this idea because if I do this
In a single thread:
while(usr_input != true)
{
read_file_in_thread(file,buf,BUF_SIZE);
}
Where "read_file_in_thread" is done as:(only excerpt shown to save time, apologies)
read_file_in_thread(ifstream file_to_read, char * buf, int size_of_buf){
...
int pos = 0;
while(!file_to_read.eof())
{
file_to_read >> buf[pos++];
if(pos>=BUF_SIZE) break;
}
}
And file write operations in the almost identical fashion with (again, excerpt, my apologies)
file_to_write<<buf[pos++];
If I do the above with one 1 thread, I noticed, both reading and writing are done consecutively, no need for me to provide any information regarding last position of any file operation as if the system remembers. I suppose under the hood, C++ intentionally/unintentionally takes care of a lot of things by doing almost everything with pointers and they don't get reset that often?
Like I said when it was done with single thread the file positioning sort of is done "automatically" but no way reliably, as at some point the reading operation started right from the beginning then continued from last furthest position, that is it went like 0, 1, 2, 3, then 0, 4, 5, 6...
And when it was done by 2 threads, this "automatic positioning" behavior disappears completely, as in the reading goes like 0, 0, 0, 0, for both threads. My guess (and don't let my guess misguide you) is that when another thread sort of chimes in, something gets reset?
So ultimately, my 2 questions:
1, why when one thread is doing the operation, there is such an "automatic positioning" thing going on?
2, Is this "automatic positioning" doable, reliably, on 2 or more threads, without using functions like seekg, seekp to deliberately seek out specific file positions? Is it possible at all?
I understand that my code and my description of the question may not give a complete picture, but I hope to convey an overall idea. When solving this question you may freely add more functions and variables and many other as you please but it is not encouraged, it is advised to work with what you have given in the question.
Aucun commentaire:
Enregistrer un commentaire