diff mbox

implementation of std::thread::hardware_concurrency()

Message ID CAMPTgK2Fph+jQBtKQ+nHa7+BMdUCu=zT3dWaUO0pc7z=Xg8mWg@mail.gmail.com
State New
Headers show

Commit Message

niXman Oct. 31, 2011, 9:10 p.m. UTC
Hi all.

This is patch is implement the std::thread::hardware_concurrency().
Tested on pthreads-win32/winpthreads on windows OS, and on Linux/FreeBSD.

Comments

Paolo Carlini Oct. 31, 2011, 9:20 p.m. UTC | #1
Hi,

> This is patch is implement the std::thread::hardware_concurrency().
> Tested on pthreads-win32/winpthreads on windows OS, and on Linux/FreeBSD.

Please send library patches to the library mailing list too. Also, always parch mainline first: actually in the latter the function is alread implemented, maybe something is missing for win32, please check, rediff, and resend.

Thanks
Paolo
Richard Henderson Oct. 31, 2011, 9:27 p.m. UTC | #2
On 10/31/2011 02:10 PM, niXman wrote:
> +#elif definen(_GLIBCXX_USE_GET_NPROCS)

Typo.


r~
Mike Stump Oct. 31, 2011, 9:48 p.m. UTC | #3
On Oct 31, 2011, at 2:10 PM, niXman wrote:
> This is patch is implement the std::thread::hardware_concurrency().

[ general comment ] Ick, this isn't what I'd call clean.  Maybe a porting header inclusion that defines a static inline pthread_num_processors_np when on those system that don't have it.  With that then this routine could just use pthread_num_processors_np instead after including that porting header.  Having dozens of files with cascades of #if went out of fashion back in the 1990s.
diff mbox

Patch

diff --git a/libstdc++-v3/src/thread.cc b/libstdc++-v3/src/thread.cc
index 09e7fc5..3eacb06 100644
--- a/libstdc++-v3/src/thread.cc
+++ b/libstdc++-v3/src/thread.cc
@@ -112,10 +112,20 @@  _GLIBCXX_BEGIN_NAMESPACE_VERSION
   unsigned int
   thread::hardware_concurrency() noexcept
   {
-    int __n = _GLIBCXX_NPROCS;
-    if (__n < 0)
-      __n = 0;
-    return __n;
+    int count=0;
+#if defined(PTW32_VERSION) || \
+   (defined(__MINGW64_VERSION_MAJOR) && defined(_POSIX_THREADS)) || \
+   defined(__hpux)
+    count=pthread_num_processors_np();
+#elif defined(__APPLE__) || defined(__FreeBSD__)
+    size_t size=sizeof(count);
+    sysctlbyname("hw.ncpu", &count, &size, NULL, 0);
+#elif defined(_SC_NPROCESSORS_ONLN)
+    count=sysconf(_SC_NPROCESSORS_ONLN);
+#elif definen(_GLIBCXX_USE_GET_NPROCS)
+    count=_GLIBCXX_NPROCS;
+#endif
+    return (count>0)?count:0;
   }

 _GLIBCXX_END_NAMESPACE_VERSION