Are you concerned about optimizing out the file open operation? I think you are making it way more complex and error prone than what it should be. File pointers (FILE*
) are not thread-safe structures so you cannot share them across threads.
What you probably need to do (if you really want to cache the file open operations) is to keep a dictionary mapping filename to a file descriptor (an int
) and have a thread-safe function to return a descriptor by name or open if it's not in the dictionary.
And of course doing I/O to the same file descriptor from multiple threads needs to be regulated as well.