views:

411

answers:

2

I feel like there is an obvious answer to this, but it's been eluding me. I've got some legacy code in C++ here that breaks when it tries to call OpenThread(). I'm running it in Visual C++ 2008 Express Edition. The program first gets the ThreadID of the calling thread, and attempts to open it, like so:

ThreadId threadId = IsThreaded() ? thread_id : ::GetCurrentThreadId();

HANDLE threadHandle = OpenThread(THREAD_ALL_ACCESS, FALSE, threadId);

Now here's what I don't understand: if the thread ID is the current thread's ID, isn't it already open? Could that be why it's returning NULL?

Any feedback would be appreciated.

+2  A: 

Maybe you're asking for too much access (THREAD_ALL_ACCESS), though I'd think that you'd have pretty much all permissions to your own thread. Try reducing the access to what you really need.

What does GetLastError() return?

Update:

Take a look at this comment from MSDN:

Windows Server 2003 and Windows XP/2000: The size of the THREAD_ALL_ACCESS flag increased on Windows Server 2008 and Windows Vista. If an application compiled for Windows Server 2008 and Windows Vista is run on Windows Server 2003 or Windows XP/2000, the THREAD_ALL_ACCESS flag is too large and the function specifying this flag fails with ERROR_ACCESS_DENIED. To avoid this problem, specify the minimum set of access rights required for the operation. If THREAD_ALL_ACCESS must be used, set _WIN32_WINNT to the minimum operating system targeted by your application (for example, #define _WIN32_WINNT _WIN32_WINNT_WINXP ). For more information, see Using the Windows Headers

Michael Burr
ThREAD_ALL_ACCESS was apparently the problem. I used THREAD_SET_INFORMATION and it did the trick. Thanks very much!
RCC
+1  A: 

Try using _beginthreadex instead of OpenThread. Example: HANDLE hThread; UINT uiThreadId = 0; hThread = (HANDLE)_beginthreadex(NULL, // Security attributes 0, // stack &this->ThreadProc, // Thread proc this, // Thread param CREATE_SUSPENDED, // creation mode &uiThreadId); // Thread ID

if ( hThread != NULL){ //SetThreadPriority(hThread, THREAD_PRIORITY_HIGHEST); ResumeThread( hThread ); m_hThread = hThread; } else { eRetVal = err_ThreadStartErr; }

Viraj