Page 1 of 1

ThreadID()

Posted: Sat Jun 19, 2010 6:30 pm
by cas
OS: Windows 7 x64, PB4.50 x86
Here is sample code (enable threadsafe in compiler):

Code: Select all

Procedure test(void)
  Debug "GetCurrentThreadId() = "+Str(GetCurrentThreadId_())
EndProcedure

Define thread=CreateThread(@test(),0)
If thread
  Debug "ThreadID() = "+Str(ThreadID(thread))
EndIf

WaitThread(thread)
So when i run it i get something like this:
ThreadID() = 192
GetCurrentThreadId() = 3044
How to get that '3044' outside of thread test()?

Thanks

Re: ThreadID()

Posted: Sat Jun 19, 2010 6:43 pm
by DarkPlayer
Hello,

The PureBasic command ThreadID() returns the Handle of the Thread and GetCurrentThreadId_() returns the real ID. The names of the commands are a bit confusing.

Dark

Re: ThreadID()

Posted: Sat Jun 19, 2010 11:48 pm
by cas
Yes, i know that but my question was how to get that 'real' ID.

Re: ThreadID()

Posted: Sun Jun 20, 2010 2:02 am
by DarkPlayer
Hello,

You have three possibilities:

1. you can use the native CreateThread_() API command, which gives use also the real id
2. on Vista and higher, you can use the GetThreadId() API.
3. you can use these undocumented NT API calls on Windows 2000/XP/Vista/7:

Code: Select all

Structure CLIENT_ID
   UniqueProcess.i;
   UniqueThread.i;
EndStructure

Structure THREAD_BASIC_INFORMATION
  ExitStatus.l;
  TebBaseAddress.i;
  ClientId.CLIENT_ID;
  AffinityMask.l;
  Priority.l;
  BasePriority.l;
EndStructure

Enumeration
  #ThreadBasicInformation
  #ThreadTimes
  #ThreadPriority
  #ThreadBasePriority
  #ThreadAffinityMask
  #ThreadImpersonationToken
  #ThreadDescriptorTableEntry
  #ThreadEnableAlignmentFaultFixup
  #ThreadEventPair
  #ThreadQuerySetWin32StartAddress
  #ThreadZeroTlsCell
  #ThreadPerformanceCount
  #ThreadAmILastThread
  #ThreadIdealProcessor
  #ThreadPriorityBoost
  #ThreadSetTlsArrayAddress
  #ThreadIsIoPending
  #ThreadHideFromDebugger
  #ThreadBreakOnTermination
  #ThreadSwitchLegacyState
  #ThreadIsTerminated
  #ThreadLastSystemCall
  #ThreadIoPriority
  #ThreadCycleTime
  #ThreadPagePriority
  #ThreadActualBasePriority
  #ThreadTebInformation
  #ThreadCSwitchMon
EndEnumeration

Procedure GetThreadIDFromHandle(Handle.i)

  Protected Info.THREAD_BASIC_INFORMATION
 
  If NtQueryInformationThread_(Handle, #ThreadBasicInformation, @Info, SizeOf(Info),0) = 0
    ProcedureReturn Info\ClientId\UniqueThread
  EndIf

EndProcedure
TestCode:

Code: Select all

Procedure Test(a.i)
  Debug GetCurrentThreadId_()
  Repeat
    Delay(10)
  ForEver

EndProcedure

HThread = CreateThread(@Test(),0)

Debug GetThreadIDFromHandle(ThreadID(HThread))
DarkPlayer

Re: ThreadID()

Posted: Sun Jun 20, 2010 10:56 am
by cas
Thanks for this nice post, it solves my problem perfectly. :P