I've got an application with multiple threads. They are all reading from a single disk file. The following code works fine on Windows, but produces bad data restults on the Mac:
threadFunction() {
FILE* f = ...;
for (..) {
pthread_mutex_lock(); // ensure threads dont interfere with each other
fseek ( .... , f);
fread ( .... , f);
pthread_mutex_unlock();
} // end for
} // end thread function
On Windows, the above code works fine. On the Mac, it runs, but the data returned from fread() is from the wrong part of the disk file: namely, a part of the file being read by antoher thread. Clearly, the FILE* buffers are getting mixed up between the threads. Yet I am carefule to ensure that each thread has its own dedicated FILE* object.
I can get it to work on the Mac by placing a call to fpurge() as follows ... but this is not really satisfactory because it slows down the threads:
threadFunction() {
FILE* f = ...;
for (..) {
pthread_mutex_lock(); // ensure threads dont interfere with each other
fseek ( .... , f);
fread ( .... , f);
fpurge ( f ); // slows down read rate
pthread_mutex_unlock();
} // end for
} // end thread function
Any ideas why the first pseudo code (without fpurge) produces bad results from fread()? Is the stdio library thread safe?
Thanks in advance for any help,
neal
threadFunction() {
FILE* f = ...;
for (..) {
pthread_mutex_lock(); // ensure threads dont interfere with each other
fseek ( .... , f);
fread ( .... , f);
pthread_mutex_unlock();
} // end for
} // end thread function
On Windows, the above code works fine. On the Mac, it runs, but the data returned from fread() is from the wrong part of the disk file: namely, a part of the file being read by antoher thread. Clearly, the FILE* buffers are getting mixed up between the threads. Yet I am carefule to ensure that each thread has its own dedicated FILE* object.
I can get it to work on the Mac by placing a call to fpurge() as follows ... but this is not really satisfactory because it slows down the threads:
threadFunction() {
FILE* f = ...;
for (..) {
pthread_mutex_lock(); // ensure threads dont interfere with each other
fseek ( .... , f);
fread ( .... , f);
fpurge ( f ); // slows down read rate
pthread_mutex_unlock();
} // end for
} // end thread function
Any ideas why the first pseudo code (without fpurge) produces bad results from fread()? Is the stdio library thread safe?
Thanks in advance for any help,
neal