views:

66

answers:

4

Is it correct to assume that GetLastError (and variants) are per-thread or is it per-process? The problems if it is per-process are somewhat obvious in multithreaded apps because there is no way to guarentee that no other Win32 calls were made between your failed call and GetLastError. Sometimes the value of GetLastError is important.

For example, AcceptEx will return FALSE (failure) if you are using IO completion ports. WSAGetLastError (similar to GetLastError) will return ERROR_IO_PENDING to inform you that it is pended and the failure is not due to something else. The problem is that dozens of ofther calls can be in flight and overwrite this value.

Are these calls thread specific or process specific? If process specific then how do you handle this correctly?

A: 

According to this page http://msdn.microsoft.com/en-us/library/ms679360(VS.85).aspx GetLastError returns the error of the calling thread (not process).

This is a good question, since the UNIX equivalent (errno) is not thread safe!

Starkey
Per http://unix.derkeiler.com/Newsgroups/comp.unix.programmer/2007-05/msg00286.html , """errno is thread-safe on all platforms that support POSIXthreads, *provided* you compile your code correctly.How to do so depends on the platform. On Solaris, compile with-D_REENTRANT, on AIX with -D_THREAD_SAFE. On Linux, compile with'-pthread' (though Linux errno is thread-safe by default)."""
Alex Martelli
-1 for misinformation about errno.
R..
+1  A: 

Both GetLastError and WSAGetLastError return per-thread error codes. Have a look at the MSDN entries:

  • GetLastError: The return value is the calling thread's last-error code.
  • WSAGetLastError: The WSAGetLastError function returns the last error that occurred for the calling thread.
casablanca
+6  A: 

the docs are absolutely unambiguous about this:

GetLastError Function

Retrieves the calling thread's last-error code value. The last-error code is maintained on a per-thread basis. Multiple threads do not overwrite each other's last-error code.

So they said it three times (in a single paragraph!): should be enough, as Lewis Carroll said;-). Thus there's no need to answer hypotheticals such as "but if it was per-process rather than per thread, then what about...?";-).

Alex Martelli
+1 for mentioning Lewis Carroll.
Praveen S
I must be blind because I didn't see it in the MSDN docs until everyone pointed it out.
Karl Strings
+1 for pointing out the obvious.
Karl Strings
A: 

You can read on MSDN (see http://msdn.microsoft.com/en-us/library/ms679360.aspx) clear answer on your question:

Retrieves the calling thread's last-error code value. The last-error code is maintained on a per-thread basis. Multiple threads do not overwrite each other's last-error code.

Oleg