'Is it possible to share file pointers between threads?

We need to address some performance issues on our application. Using Visual Studio's diagnostic hub, we discovered that file operations were responsible for our issue.

We are using a file to save critical data temporarily that has to be sent via TCP/IP to a server.

The file consists of a header where information is stored, where to find a specific data set (offset and length of up to 2500 data sets in this file). The second part is the data itself, addressed by the information in the header.

When data is written to the file, first the header is read, then data is written to the next empty location, and the information in the header is updated and written again.

When data needs to be sent (in the second thread), the header is read to obtain the next offset and length of data to be read. Then the data is read and sent via TCP/IP. Until we receive the TCP/IP ACK of the server, the header is not updated again. When the ACK arrives, the header information is updated to reflect that the used dataset is now empty.

All functions involved in this process made a fopen() and fclose() to the file, which caused our performance issues.

I know that there must be some synchronization when writing the header, because when the first thread puts in new data, the second thread must obey the new write pointer in the file (if not, the newly written data will be lost).

If I am able to sync access to the file pointer, so that any time one thread is writing at a specific location, the other thread would not write too, is it safe to use the FILE* variable in those two threads?

Or, would it be better to have two FILE* variables that read and write on their own portions of the file?

I know, that I could combine both operations into one thread, but then I must address delays from synchronous socket operations.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source