Page 1 of 1

Set Thread name

Posted: Thu Jun 22, 2023 9:16 am
by tatanas
Hi,

For those interested, for debug purpose, here is a way to get/set the name of your program threads :

Code: Select all

ImportC "-pthread"
	pthread_setname_np(threadID.i, *name) ; set name of the thread
	pthread_getname_np(threadID.i, *name, len.i) ; get name of the thread
	pthread_self() ; use directly inside the thread to get the thread id (equivalent to ThreadID())
EndImport
	
	
; the name should not exceed 16 bytes (including the terminating null byte ('\0'))
Procedure SetThreadName(ThreadID.i, Name.s)
	Protected *name_buff

	If StringByteLength(Name, #PB_Ascii) <= 15
		*name_buff = AllocateMemory(16)
		If *name_buff
			PokeS(*name_buff, Name, -1, #PB_Ascii)
			pthread_setname_np(ThreadID, *name_buff)
			FreeMemory(*name_buff)
			ProcedureReturn 1
		EndIf
	EndIf
	ProcedureReturn 0
EndProcedure


; Get the name of the Thread
; - current thread if ThreadID = 0 (use this function inside the wanted thread)
; - specified thread if ThreadID = ThreadId(yourthread)
; will return 15 char max (thread name can't exceed 15 char)
Procedure.s GetThreadName(ThreadID.i = 0)
	Protected *name_buff
	Protected th_id
	Protected Name$

	*name_buff = AllocateMemory(16)
	If *name_buff
		If ThreadID = 0
			th_id = pthread_self()
		Else
			th_id = ThreadID
		EndIf
		pthread_getname_np(th_id, *name_buff, 16)
		Name$ = PeekS(*name_buff, -1, #PB_Ascii)
		FreeMemory(*name_buff)
		ProcedureReturn Name$
	EndIf
	ProcedureReturn ""
EndProcedure

Re: Set Thread name

Posted: Thu Jun 22, 2023 1:52 pm
by Caronte3D
Useful, thanks! :wink:

Re: Set Thread name

Posted: Thu Jun 22, 2023 2:21 pm
by jacdelad
Ok, im blind and/or stupid...but...why?

Re: Set Thread name

Posted: Thu Jun 22, 2023 3:57 pm
by Fred
Logging mainly.