libs/libc: replace critical section with spinlock in hostname operations

Replace global enter_critical_section() with lightweight spinlock in
gethostname() and sethostname() to reduce interrupt latency while protecting
access to the shared hostname string.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
This commit is contained in:
hujun5
2025-03-09 08:38:07 +08:00
committed by GUIDINGLI
parent 4a160e7778
commit acc833b07d
2 changed files with 8 additions and 4 deletions
+4 -2
View File
@@ -46,6 +46,7 @@
#include <unistd.h>
#include <nuttx/irq.h>
#include <nuttx/spinlock.h>
/* Further, in the protected and kernel build modes where kernel and
* application code are separated, the hostname is a common system property
@@ -74,6 +75,7 @@
/* This is the system hostname */
char g_hostname[HOST_NAME_MAX + 1] = CONFIG_LIBC_HOSTNAME;
spinlock_t g_hostname_lock = SP_UNLOCKED;
/****************************************************************************
* Public Functions
@@ -111,9 +113,9 @@ int gethostname(FAR char *name, size_t namelen)
* that it could change while we are copying it.
*/
flags = enter_critical_section();
flags = spin_lock_irqsave(&g_hostname_lock);
strlcpy(name, g_hostname, namelen);
leave_critical_section(flags);
spin_unlock_irqrestore(&g_hostname_lock, flags);
return 0;
}
+4 -2
View File
@@ -47,6 +47,7 @@
#include <unistd.h>
#include <nuttx/irq.h>
#include <nuttx/spinlock.h>
/* Further, in the protected and kernel build modes where kernel and
* application code are separated, the hostname is a common system property
@@ -67,6 +68,7 @@
/* This is the system hostname (defined in lib_gethostname). */
extern char g_hostname[HOST_NAME_MAX + 1];
extern spinlock_t g_hostname_lock;
/****************************************************************************
* Public Functions
@@ -105,9 +107,9 @@ int sethostname(FAR const char *name, size_t namelen)
* are setting it.
*/
flags = enter_critical_section();
flags = spin_lock_irqsave(&g_hostname_lock);
strlcpy(g_hostname, name, sizeof(g_hostname));
leave_critical_section(flags);
spin_unlock_irqrestore(&g_hostname_lock, flags);
return 0;
}