Set Thread name

Linux specific forum
tatanas
Enthusiast
Enthusiast
Posts: 260
Joined: Wed Nov 06, 2019 10:28 am
Location: France

Set Thread name

Post 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
Windows 10 Pro x64
PureBasic 6.20 x64
User avatar
Caronte3D
Addict
Addict
Posts: 1361
Joined: Fri Jan 22, 2016 5:33 pm
Location: Some Universe

Re: Set Thread name

Post by Caronte3D »

Useful, thanks! :wink:
User avatar
jacdelad
Addict
Addict
Posts: 2010
Joined: Wed Feb 03, 2021 12:46 pm
Location: Riesa

Re: Set Thread name

Post by jacdelad »

Ok, im blind and/or stupid...but...why?
Good morning, that's a nice tnetennba!

PureBasic 6.21/Windows 11 x64/Ryzen 7900X/32GB RAM/3TB SSD
Synology DS1821+/DX517, 130.9TB+50.8TB+2TB SSD
Fred
Administrator
Administrator
Posts: 18220
Joined: Fri May 17, 2002 4:39 pm
Location: France
Contact:

Re: Set Thread name

Post by Fred »

Logging mainly.
Post Reply