Lefteris
Lefteris

Reputation: 3256

Winapi Error 87 at start of Thread

I have a problem that has been bothering me for a while. Each child thread in my project is running correctly and does what it is supposed to do with the exception of beginning the thread with Last Error set at 87.

87 means invalid parameter according to Win32 System errors. Since LastError is thread-specific, and since from the very first line of the ThreadProc function it appears to be set the only thing I can deduce is that the ThreadProc function itself is somehow wrong syntactically(?).

My OS is Windows 7 x64 and the compiler is gcc version 4.6.2 I have made a small example program which in my system starts the child thread with error 87 set.

#include <windows.h>

DWORD WINAPI THREAD_FUNCTION(LPVOID t)
{
    printf("In the child thread: Last Error is %lu\n",GetLastError());
    return 0;
}

typedef struct thread_data
{
    //just an id for example's sake
    uint32_t id;
}thread_data;

int main()
{
    HANDLE thread;
    thread_data d;
    d.id = 1;
    printf("Main thread start:Last error is %lu\n",GetLastError());
    //create the thread
    thread = CreateThread(NULL,0, (LPTHREAD_START_ROUTINE) THREAD_FUNCTION,(LPVOID)&d,0, NULL);
    //wait for it
    WaitForSingleObject(thread,INFINITE);
    CloseHandle(thread);
    printf("Main thread finish: Last error is %lu\n",GetLastError());
    return 0;
}

This outputs:

Main thread start:Last error is 0
In the thread: Last Error is 87
Main thread finish: Last error is 0

I assume it is an error of the way I call the thread and pass data to it but I can't deduce this error by reading the documentation. Any ideas?

Upvotes: 1

Views: 2029

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

You have to remember that the last error is only reliable if the last function called returns an error.

Upvotes: 3

shf301
shf301

Reputation: 31394

The return value of GetLastError() in your example is meaningless. Calling GetLastError() is only valid immediately after calling a Windows API function that sets the last error value (the MSDN documentation for state whether a given function does so or not).

In your thread routine you are calling GetLastError() without calling any Windows API functions that would set it, so its return value doesn't reflect any error that your code caused so it means nothing to you.

It's possible that the value of GetLastError() are a newly started thread is completely meaningless - that it's just random that it is set to 87. More likely there is some code that executes during thread setup that generates the 87 error. If this code was build in Visual Studio or run on a different version of Windows you may get a different value. But no matter what it's not something that you can control or rely on or even need to care about.

Upvotes: 5

Related Questions