Multi-Threaded IO Problems

Multi-Threaded IO Problems

Post by Gary Coo » Thu, 22 Apr 2004 05:22:13


This is a multi-part message in MIME format.



We are seeing the following function fail on a multiple CPU machine if it is called at the same time from two separate threads.
I do not believe the problem is with the file descriptor since I also see the crash if one thread (not my code) is doing a FSWrite on an entirely different descriptor while another thread is invoking this method.

Is there something un-thread-safe about the I/O calls I am making? What is the alternative?

void logStuff(const char *logEntry) {
FILE *fsource = fopen(logFile,"a");
if(fsource) {
fprintf(fsource,"%s",logEntry);
fflush(fsource);
fclose(fsource);
}
}

Note:
logFile is a global variable that does not change (it is in CFM format).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<META content="MSHTML 6.00.2800.1400" name=GENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=#ffffff background="">
<DIV><FONT face=Arial size=2>We are seeing the following function fail on a
multiple CPU machine if it is called at the same time from two separate
threads.<BR>I do not believe the problem is with the file descriptor since I
also see the crash if one thread (not my code) is doing a FSWrite on an entirely
different descriptor while another thread is invoking this
method.<BR> <BR>Is there something un-thread-safe about the I/O calls I am
making?  What is the alternative?<BR> <BR>void logStuff(const char
*logEntry)
{<BR>           
FILE                
*fsource =
fopen(logFile,"a");<BR>           
if(fsource) {</FONT></DIV>
<DIV><FONT face=Arial
size=2>                       
fprintf(fsource,"%s",logEntry);<BR>                       
fflush(fsource);<BR>                       
fclose(fsource);<BR>           
}          
<BR>}<BR> <BR>Note:<BR>logFile is a global variable that does not change
(it is in CFM format).</FONT></DIV></BODY></HTML>
 
 
 

Multi-Threaded IO Problems

Post by David Phil » Thu, 22 Apr 2004 16:10:33

In article < XXXX@XXXXX.COM >,



Do you have your Metrowerks standard library recompiled with thread
safety turned on?


// initialized with MPCreateCriticalRegion,
// a global available to all threads
MPCriticalRegionID globalCriticalRegion;


// Rename your logStuff, above, to "logStuffInner" and:


void logStuff(const char *logEntry) {
OSStatus err = MPEnterCriticalRegion(
globalCriticalRegion,
kDurationMillisecond * 1000); // 1 sec timeout
if(noErr == err){
logStuffInner(logEntry);
MPExitCriticalRegion(globalCriticalRegion);
}
}

that is, only one thread can call logStuffInner() at a time. Other
threads that try will block until the first thread exits the critical
section.