PRB: _mktemp() May Return the Same Name Between Threads (114374)
The information in this article applies to:
This article was previously published under Q114374 SYMPTOMS
When calling _mktemp() with the same template name in different threads of
the same process, _mktemp() may return the same file name to each thread.
CAUSE
The _mktemp() function is used to generate temporary file names. Starting
with a user supplied template consisting of a base followed by six X's,
_mktemp() generates temporary file names by concatenating a five digit
value to the specified base. To ensure that unique names are generated
between processes, the process id is encoded into the file name. In a multi-
threaded application, the scheme of using only the process id makes it
possible for threads to receive the same temporary file name. This could
occur whenever one of the file names returned by _mktemp had not actually
been used to open a file yet.
RESOLUTION
In Visual C++ 2.0, _mktemp() uses the thread id in generating the name, so
this problem will not occur.
In Visual C++ 1.0, the work-around is to pass in a different template name
to _mktemp() in each thread. A convenient way to create a unique template
name for a thread would be to use the thread id to generate the template
name. In the code fragment below, the thread id is obtained and used as an
index into a set of characters which are used as the first two characters
in the template name.
#define DIG_LEN 37
static char digits [ DIG_LEN + 1 ] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_";
// Within the thread, generate a template name
// using the thread id.
char templte[9];
unsigned tid = GetCurrentThreadId();
strcpy ( templte , "@@XXXXXX" ); // initialize template name
templte[0] = digits [ tid % DIG_LEN ]; // assign first character
// in template name using
// the tid to index into
// the digits array
templte[1] =
digits [ ( tid / DIG_LEN ) % DIG_LEN ]; // second character
path1 = _mktemp(templte);
Modification Type: | Major | Last Reviewed: | 10/2/2003 |
---|
Keywords: | kbCRT kbprb KB114374 |
---|
|