From af6feaa45c4a865f91eb8c1b049e51dffa2e7456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Storsj=C3=B6?= Date: Tue, 21 Jan 2014 12:19:22 +0200 Subject: [PATCH] Use sched_getaffinity to get the number of cores on linux This gets rid of the code that parses /proc/cpuinfo, and avoids forking within the library. The previous code also failed build on modern glibc versions due to ignoring the return value of the system, read and write system calls. --- codec/common/WelsThreadLib.cpp | 61 +++++++--------------------------- 1 file changed, 12 insertions(+), 49 deletions(-) diff --git a/codec/common/WelsThreadLib.cpp b/codec/common/WelsThreadLib.cpp index 98de1449..bbbb3146 100644 --- a/codec/common/WelsThreadLib.cpp +++ b/codec/common/WelsThreadLib.cpp @@ -39,6 +39,13 @@ */ +#ifdef LINUX +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#include +#endif + #include "WelsThreadLib.h" #include @@ -180,47 +187,6 @@ WELS_THREAD_ERROR_CODE WelsQueryLogicalProcessInfo (WelsLogicalProcessInfo* p //#include #endif//MACOS -static int32_t SystemCall (const str_t* pCmd, str_t* pRes, int32_t iSize) { - int32_t fd[2]; - int32_t iPid; - int32_t iCount; - int32_t left; - str_t* p = NULL; - int32_t iMaxLen = iSize - 1; - memset (pRes, 0, iSize); - - if (pipe (fd)) { - return -1; - } - - if ((iPid = fork()) == 0) { - int32_t fd2[2]; - if (pipe (fd2)) { - return -1; - } - close (STDOUT_FILENO); - dup2 (fd2[1], STDOUT_FILENO); - close (fd[0]); - close (fd2[1]); - system (pCmd); - read (fd2[0], pRes, iMaxLen); - write (fd[1], pRes, strlen (pRes)); // confirmed_safe_unsafe_usage - close (fd2[0]); - close (fd[1]); - exit (0); - } - close (fd[1]); - p = pRes; - left = iMaxLen; - while ((iCount = read (fd[0], p, left))) { - p += iCount; - left -= iCount; - if (left <= 0) break; - } - close (fd[0]); - return 0; -} - void WelsSleep (uint32_t dwMilliseconds) { usleep (dwMilliseconds * 1000); // microseconds } @@ -483,19 +449,16 @@ WELS_THREAD_ERROR_CODE WelsMultipleEventsWaitAllBlocking (uint32_t nCount, WE WELS_THREAD_ERROR_CODE WelsQueryLogicalProcessInfo (WelsLogicalProcessInfo* pInfo) { #ifdef LINUX -#define CMD_RES_SIZE 2048 - str_t pBuf[CMD_RES_SIZE]; + cpu_set_t cpuset; - SystemCall ("cat /proc/cpuinfo | grep \"processor\" | wc -l", pBuf, CMD_RES_SIZE); + CPU_ZERO (&cpuset); - pInfo->ProcessorCount = atoi (pBuf); - - if (pInfo->ProcessorCount == 0) { + if (!sched_getaffinity (0, sizeof (cpuset), &cpuset)) + pInfo->ProcessorCount = CPU_COUNT (&cpuset); + else pInfo->ProcessorCount = 1; - } return WELS_THREAD_ERROR_OK; -#undef CMD_RES_SIZE #else