-
Notifications
You must be signed in to change notification settings - Fork 23
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Decouple CPU routines to dedicated header
atoi() is considered unsafe. Use strtol instead. C99 standard [7.20.1] : The functions atof, atoi, atol, and atoll need not affect the value of the integer expression errno on an error. If the value of the result cannot be represented, the behavior is undefined.
- Loading branch information
Showing
3 changed files
with
74 additions
and
66 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
/* | ||
* Copyright (C) 2018 dcurl Developers. | ||
* Use of this source code is governed by MIT license that can be | ||
* found in the LICENSE file. | ||
*/ | ||
|
||
#include <errno.h> | ||
#include <stdlib.h> | ||
|
||
/* Required for get_nprocs_conf() on Linux */ | ||
#if defined(__linux__) | ||
#include <sys/sysinfo.h> | ||
#endif | ||
|
||
/* On Mac OS X, define our own get_nprocs_conf() */ | ||
#if defined(__APPLE__) || defined(__FreeBSD__) | ||
#include <sys/sysctl.h> | ||
static unsigned int get_nprocs_conf() | ||
{ | ||
int num_proc = 0; | ||
size_t size = sizeof(num_proc); | ||
if (sysctlbyname("hw.ncpu", &num_proc, &size, NULL, 0)) | ||
return 1; | ||
return (unsigned int) num_proc; | ||
} | ||
#endif | ||
|
||
static inline int get_avail_nprocs() | ||
{ | ||
size_t nproc = get_nprocs_conf() - 1; | ||
|
||
do { | ||
char *env_ncpu = getenv("DCURL_NUM_CPU"); | ||
if (!env_ncpu) { | ||
break; | ||
} | ||
|
||
char *end; | ||
signed int num = strtol(env_ncpu, &end, 10); | ||
if (end == env_ncpu) { | ||
/* if no characters were converted these pointers are equal */ | ||
break; | ||
} | ||
if (errno == ERANGE || num > INT_MAX || num < 0) { | ||
/* because strtol produces a long, check for overflow */ | ||
break; | ||
} | ||
nproc = num; | ||
} while (0); | ||
|
||
if (!nproc) | ||
nproc = 1; | ||
return nproc; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters