Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper handling of GetLastError (and others) in a multithreaded context

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?

like image 992
Karl Strings Avatar asked Aug 06 '10 17:08

Karl Strings


3 Answers

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...?";-).

like image 171
Alex Martelli Avatar answered Oct 09 '22 08:10

Alex Martelli


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.
like image 32
casablanca Avatar answered Oct 09 '22 08:10

casablanca


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.

like image 34
Oleg Avatar answered Oct 09 '22 07:10

Oleg