git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH 2/2] thread-utils.c: detect CPU count on older BSD-like systems

From
Kyle J. McKay <mackyle@gmail.com>
Date
Mar 8, 2015, 07:14 UTC
Message-ID
<087595269450d378dbaf0188e8f65c5@74d39fa044aa309eaea14b9f57fe79c>
In-Reply-To
<e85cd4def375e8247ab210983e44e75@74d39fa044aa309eaea14b9f57fe79c>

Not all systems support using sysconf to detect the number of available CPU cores. Older BSD and BSD-derived systems only provide the information via the sysctl function.

If HAVE_BSD_SYSCTL is defined attempt to retrieve the number of available CPU cores using the sysctl function.

If HAVE_BSD_SYSCTL is not defined or the sysctl function fails, we still attempt to get the information via sysconf.

Signed-off-by: Kyle J. McKay <mackyle@gmail.com>
---
 thread-utils.c | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)
diff --git a/thread-utils.c b/thread-utils.c
index 97396a75..a2135e07 100644
--- a/thread-utils.c
+++ b/thread-utils.c
@@ -35,7 +35,23 @@ int online_cpus(void)
 
 	if (!pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0))
 		return (int)psd.psd_proc_cnt;
-#endif
+#elif defined(HAVE_BSD_SYSCTL) && defined(HW_NCPU)
+	int mib[2];
+	size_t len;
+	int cpucount;
+
+	mib[0] = CTL_HW;
+#  ifdef HW_AVAILCPU
+	mib[1] = HW_AVAILCPU;
+	len = sizeof(cpucount);
+	if (!sysctl(mib, 2, &cpucount, &len, NULL, 0))
+		return cpucount;
+#  endif /* HW_AVAILCPU */
+	mib[1] = HW_NCPU;
+	len = sizeof(cpucount);
+	if (!sysctl(mib, 2, &cpucount, &len, NULL, 0))
+		return cpucount;
+#endif /* defined(HAVE_BSD_SYSCTL) && defined(HW_NCPU) */
 
 #ifdef _SC_NPROCESSORS_ONLN
 	if ((ncpus = (long)sysconf(_SC_NPROCESSORS_ONLN)) > 0)
---
Previous: Kyle J. McKay
Message 2 of 2 in “configure: support HAVE_BSD_SYSCTL option”
  1. 1/2 configure: support HAVE_BSD_SYSCTL optionKyle J. McKay, Mar 8, 2015
  2. 2/2 thread-utils.c: detect CPU count on older BSD-like systemsKyle J. McKay, Mar 8, 2015

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.